---
title: Migrate from InstantDB Cloud to Kovlet
overline: HOW-TO
nav: Migrate from InstantDB
updated: 2026-12
reviewed: 2026-12
minutes: 10
next: compare
---

# Migrate from InstantDB Cloud to Kovlet

InstantDB Cloud shuts down on August 31, 2027, according to [Instant's announcement](https://www.instantdb.com/essays/instant_team_joins_openai). One command moves your app's schema, data, files and users into Kovlet.

> **At a glance**
>
> - `kovlet-mcp migrate instantdb` copies tables, rows and files, and keeps every row id.
> - Tables, queries and realtime map one to one.
> - `$users` become the Data Space's [end users](/docs/end-users), with the same ids and emails. Magic codes, OAuth, Clerk and Firebase tokens, and guests work the same way.
> - End users can't read a table until a rule allows it. The command writes a `"true"` rule wherever InstantDB was open only because no rule was set.
> - Team members get Users × Machines × Apps grants instead of rules. Files become Data Space files.

> **Note:** InstantDB Cloud's new signups are already closed, according to the same announcement (checked December 2026). It keeps backups until August 31, 2028. It points to Instant's [self-hosting guide](https://www.instantdb.com/docs/self-hosting) as the other way to keep an app running. Check Instant's site for changes after December 2026.

This guide shows the command first. Then it maps each InstantDB concept to Kovlet and walks through the same changes by hand.

## Before you start

- [ ] An InstantDB app you can export data from.
- [ ] A free Kovlet account at kovlet.com.
- [ ] Node.js 22.12 or newer (`@kovlet/mcp` needs it; the SDKs need 22).

## Migrate in one command

Run the command from your InstantDB app's folder. It:

- reads the app id from `.env*`, plus `instant.schema.ts` and `instant.perms.ts`
- signs you in to Kovlet in the browser
- copies everything into a new Data Space

```sh title="terminal"
INSTANT_APP_ADMIN_TOKEN=<admin token> npx @kovlet/mcp migrate instantdb --dry-run
INSTANT_APP_ADMIN_TOKEN=<admin token> npx @kovlet/mcp migrate instantdb
```

The admin token comes from the InstantDB dashboard. Pass it in `INSTANT_APP_ADMIN_TOKEN`, with `--admin-token`, or type it at the hidden prompt. It is never written to disk.

The first run shows the plan and asks before it writes anything.

When it finishes, your app's folder has three new files.

> **You should see**
>
> - `kovlet.ts`: the `createKovletClient` config for the migrated tables.
> - `kovlet.perms.json`: the rules for end users, translated from `instant.perms.ts`. The command doesn't apply them (see [step 4](#4-move-permissions)).
> - `KOVLET_MIGRATION.md`: the report, the end-user import counts, the proposed access and rules, and a prompt for your coding agent.

> **Caution:** Pause writes to your InstantDB app while the command runs. Rows written during the copy can be missed. The final check reports them, and running the command again copies them.

| Option | What it does |
| --- | --- |
| `--dry-run` | Prints the plan and the counts. Writes nothing. |
| `--yes` | Skips the confirmation, for CI and coding agents. |
| `--space <id>` | Imports into an existing Data Space instead of a new one. |
| `--name <name>` | Names the new Data Space. The default is your `package.json` name. |
| `--only <entity,…>` | Migrates only these entities. `$users` and `$files` are left out. |
| `--no-users` | Doesn't import `$users` into the end-user directory. |
| `--url <url>` | Uses another Kovlet server, such as `http://127.0.0.1:8080` for `kovletd --dev`. |
| `--app-id <id>` | Sets the InstantDB app id when `.env*` doesn't have it. |
| `--admin-token <token>` | Sets the InstantDB admin token. |

> **Note:** Importing `$users` copies personal data into Kovlet: every user's id and email address. Kovlet stores it for you as a processor. Pass `--no-users` to leave it out. You can import later by running the command again.

Running the command again is safe. Rows, files and end users already in Kovlet are skipped. So a run that stopped halfway carries on where it stopped, and creates no duplicates.

The command's exit code tells you how it went:

- `0`: every row, file and importable end user is in Kovlet.
- `1`: something failed or the counts differ. Run it again.
- `2`: a usage error.
- `3`: the import doesn't fit your plan. The command writes nothing and prints what is over the limit.

### Let your coding agent do it

Paste this prompt into Claude Code, Cursor or another coding agent. Open the agent in your app's folder first.

```text title="Prompt: Migrate this app from InstantDB to Kovlet"
Migrate this app from InstantDB to Kovlet.
1. Run `npx @kovlet/mcp migrate instantdb --dry-run` in this folder and show me the plan. If it asks for the admin token, ask me for INSTANT_APP_ADMIN_TOKEN; never write it to a file.
2. When I confirm, run `npx @kovlet/mcp migrate instantdb --yes`. Show me the sign-in link it prints. If it exits with 1, run it again; if it exits with 3, stop and tell me what is over the limit.
3. Follow the agent prompt in KOVLET_MIGRATION.md to port db.useQuery, db.transact, db.storage and db.auth calls to the generated kovlet.ts.
4. Run the typecheck and tests, and list the access changes and the end-user rules (kovlet.perms.json) from KOVLET_MIGRATION.md for me to apply in the Kovlet console.
```

## What the command does

1. **Finds the app.** It reads the app id from `INSTANT_APP_ID`, `NEXT_PUBLIC_INSTANT_APP_ID`, `VITE_INSTANT_APP_ID` or a similar variable in `.env*`. It loads `instant.schema.ts` and `instant.perms.ts`. With no schema file, it tells you to run `npx instant-cli pull` first.
2. **Maps the schema.** Each entity becomes a table and each attribute becomes a column. `string`, `number` and `boolean` keep their type. `date` becomes `t.datetime()`, and `json` becomes `t.json()`. Names that Kovlet doesn't allow, such as `due-date`, are renamed to `due_date`.
3. **Maps links.** Each link becomes a reference column or a join table (see below).
4. **Checks your plan's limits first.** It counts the new rows and file bytes, and compares them with the plan's limits. If the import doesn't fit, it stops before writing anything.
5. **Copies the rows.** It reads every entity through the InstantDB Admin HTTP API, 500 rows at a time. It then writes the rows in batches with their original ids. Rows already in Kovlet are compared first, and only missing or changed rows are written.
6. **Copies the files.** `$files` become Data Space files with the same paths. Kovlet file ids are unique across all Data Spaces. So each file gets an id derived from the Data Space and its InstantDB id, and file columns are rewritten to match. Importing the same app into two Data Spaces works.
7. **Imports `$users`.** Each user's id and email go into the Data Space's end-user directory (`POST /v1/spaces/{space}/end-users`).
   - This happens before the rows, so `t.ref("_users")` columns point at users that exist.
   - Users keep their ids and sign in again with the same email.
   - Users already there are counted and skipped.
   - Guests without an email, and a second user with the same email, are skipped and listed.
   - Other profile attributes on `$users` aren't copied. Keep them in an app table with a `t.ref("_users")` column.
   - `--no-users` skips this step.
8. **Proposes access.** It translates `instant.perms.ts` two ways. Team members get Users × Machines × Apps roles, using the table in [step 4](#members-roles). End users get a rules document, `kovlet.perms.json`. It applies neither.
9. **Writes code.** It writes `kovlet.ts`, `kovlet.perms.json` and `KOVLET_MIGRATION.md`. If `kovlet.ts` already exists and wasn't generated by the command, it writes `kovlet.instantdb.ts` instead. It never changes your app's source.
10. **Checks the copy.** For every table and for the files, it checks that each InstantDB id exists in Kovlet. It counts the imported end users. It prints the counts and exits with `1` on any gap.

### How links map

| InstantDB link | Kovlet |
| --- | --- |
| Has one, such as a todo's project | A `projectId: t.ref("projects")` column on the table that has one. |
| Many to many, such as todos and tags | A join table `todos_tags` with one row per pair. Each row's id is `<todo id>:<tag id>`. |
| A link to `$files` | A `t.fileRef()` column that holds the file's new Kovlet id. |
| A link to `$users` | A `t.ref("_users")` column that keeps the InstantDB user id, which the imported end user keeps too. A many-to-many link gets a join table with a `_users` column. On a Kovlet server without end users, or a table that already has the column as a string, it stays a string column. |

Anything that can't be mapped is listed in `KOVLET_MIGRATION.md`, never dropped silently. That includes:

- values of the wrong type
- attributes missing from the schema
- `unique` or `indexed` on a json attribute (Kovlet json columns can't have either)
- rows already in the Kovlet Trash

Other `unique` and `indexed` attributes become `.unique()` and `.indexed()` columns.

## The manual path

Prefer to move one piece at a time, or want to see what each change looks like? The rest of this guide does the same migration by hand. Start with the concept mapping, then follow steps 1–6.

## Concept mapping

<!-- table: mapping -->

| InstantDB | Kovlet | Notes |
| --- | --- | --- |
| Schema: `i.schema` and `i.entity` | Tables declared in `createKovletClient` with `t.*` columns | New tables and optional columns are created on connect. |
| Queries: `db.useQuery` (nested InstaQL) | `useQuery(space, q)` in React, Vue and Svelte; `space.liveQuery(q)` elsewhere | The same tree: nested keys follow `t.ref("table")` columns forward (`author`, a row or `null`) and back (`comments`, a list). `$` takes `where`, `order`, `limit`, `after`/`before` and `fields`. Returns `{ data, isLoading, error, pageInfo }`, fully typed. |
| One table: `db.useQuery({ todos: {} })` | `useTable(table, { where, orderBy })`, or `useQuery` | `useTable` filters with a function over the local replica. |
| `db.queryOnce` | `space.query(q)` | Answers from the full replica, or `POST /v1/spaces/{space}/query`. |
| InstaQL `where`: `$in`, `$like`, `$ilike`, `$gt`, `$isNull`, `and`, `or`, `$not`, `"author.email"` | The same operators and link paths | Comparisons, `$like` and `order` on a table past 10,000 rows need an `.indexed()` column (`index_required`), as in InstantDB. |
| Pagination: `first`/`after`, `last`/`before`, `pageInfo` | `limit` with `after`/`before`, `pageInfo.endCursor` / `startCursor` | Top-level keys only, as in InstantDB. |
| Loading only what a query needs | `sync: "query"` on the space slot | Syncs the rows your queries, tables and files subscribe to (protocol 2), not the whole space. The default keeps a full offline replica. |
| Transactions: `db.transact` and `db.tx` on one entity | `table.insert`, `update`, `delete` | Writes apply locally first, queue offline, then sync. |
| `db.transact([...])` across several entities | `space.transact((tx) => { ... })`, or `POST /v1/spaces/{space}/transact` from a server | All or nothing. A rejected batch rolls back locally as one unit and reports a `TransactionRejectedError` to `onError`. Fields still merge last-writer-wins: like InstantDB's, these transactions aren't serializable. |
| `unique` and `indexed` attributes | `t.string().unique()`, `t.number().indexed()` | The server rejects a write that duplicates a unique value with `unique_violation`. Nulls never collide. Adding `.unique()` to an existing column needs an owner's approval. |
| Permissions for the app's users: `instant.perms.ts` | Rules for end users: `kovlet.perms.json`, same shape, CEL | Closed by default. Expressions carry over (`auth.id == data.owner`, `data.ref(...)`, `bind`, `ruleParams` → `params`); the server enforces them on every read and write. See the [rules reference](/docs/rules-reference#from-instantdb). |
| Permissions for your team | Roles per Data Space for users, machines and apps | Members aren't bound by rules and see every row. |
| Realtime sync | Built in for every table and file | Concurrent edits merge per field. |
| Files: `db.storage` | Data Space files: `space.files.upload` | Files are versioned and live next to the tables. |
| Rooms: `db.room(type, id)` | ``space.room(`${type}:${id}`)``, or ``useRoom(space, `${type}:${id}`)`` in React | Rooms ride on the sync socket. A room id is a label: any reader of the Data Space can join. |
| Presence: `usePresence`, `publishPresence` | `usePresence(room)` → `{ self, peers, setPresence }`; `room.setPresence` elsewhere | `setPresence` merges fields and sends at most every 50 ms. Peers carry `userId`, `machineId` and `appId`; put display names in presence. |
| Topics: `publishTopic`, `useTopicEffect` | `usePublishTopic(room, topic)` and `useTopic(room, topic, handler)`; `room.publish` and `room.onTopic` elsewhere | Fire and forget, at most once, never echoed back to the sender. |
| Typing indicators: `useTypingIndicator` | A presence field: `setPresence({ typing: true })` | No separate hook. See `examples/cursors`. |
| `$users` | `_users`, the Data Space's end-user directory | A system table. Link to it with `t.ref("_users")`. The command imports ids and emails. |
| A query through a `$users` link, e.g. todos with their owner | Nest the `t.ref("_users")` column: `useQuery(space, { todos: { ownerId: {} } })` | The owner is a row (`email`, `is_guest`, `created_at`) or `null`. The `_users` view rule decides whose profile an end user sees, like InstantDB's `$users` view permission; by default only their own. |
| `db.auth.sendMagicCode`, `signInWithMagicCode` | `kovlet.auth.sendMagicCode`, `signInWithMagicCode` | A 6-digit email code, valid 10 minutes. |
| OAuth: Google, Apple, GitHub, LinkedIn | `kovlet.auth.signInWithOAuth({ provider, redirectUri })`, then `completeOAuth()` | You register your own OAuth client with the provider, so its consent screen shows your app. |
| Clerk, Firebase or custom OIDC: `signInWithIdToken` | `kovlet.auth.signInWithIdToken({ provider, idToken })` | Configure the issuer and audience per Data Space. |
| Guests: `signInAsGuest` | `kovlet.auth.signInAsGuest()` | Signing in later attaches the identity to the guest's id. |
| `db.useAuth()` | `useAuth()` → `{ user, isLoading, error }` | |
| Admin SDK, `asUser` | A Machine Auth Key with the `Kovlet-As-End-User` header | An owner allows it per machine grant (`impersonate`). |
| `auth.createToken` | A sign-in code: `POST /v1/spaces/{space}/end-users/{id}/sign-in-codes` | The client redeems it once with `grant_type=sign_in_code`. |
| Live queries for signed-in users | `useQuery(space, q)` / `space.liveQuery(q)` while an end user is signed in: the client syncs as them over protocol 2 ([protocol §17.9](/docs/protocol#179-end-users-on-protocol-2)). One-off reads: `kovlet.auth.records(table)` or `POST /v1/spaces/{space}/query` | Every read is filtered by the space's rules, and rows move in and out live as rules or memberships change. Sign-out clears the user's rows from the device; a token refresh keeps the subscriptions. |
| Platform API: create apps, push schema and permissions for your users' generated apps, then let them claim the app | The [partner API](/docs/partners): `POST /v1/partner/spaces`, `.../schema`, `.../rules`, `.../apps`, and a claim link from `.../transfers` | Partner keys (`kvp_`) reach the control plane only; data goes through Machine Auth Keys you mint, which the customer sees when claiming. A claim keeps every ID, so the deployed app keeps working. |

## 1. Set up Kovlet

Install the SDK in your app. If you use an AI coding agent, also connect the Kovlet MCP server.

```sh title="terminal"
npm install @kovlet/client @kovlet/react
claude mcp add kovlet -- npx -y @kovlet/mcp
```

## 2. Move your schema

Replace `instant.schema.ts` with a `kovlet.ts` that declares the same tables. Entity attributes become columns. Kovlet adds the `id` column itself.

```diff title="kovlet.ts"
-import { i } from "@instantdb/react";
+import { createKovletClient, t } from "@kovlet/client";
 
-const schema = i.schema({
-  entities: {
-    todos: i.entity({
-      text: i.string(),
-      done: i.boolean(),
-      createdAt: i.date(),
-    }),
-  },
-});
-
-export default schema;
+export const kovlet = createKovletClient({
+  appName: "Todo App",
+  autoConnect: false,
+  spaces: {
+    main: {
+      tables: {
+        todos: {
+          text: t.string(),
+          done: t.boolean(),
+          createdAt: t.datetime(),
+        },
+      },
+    },
+  },
+});
+// A stored session resumes on later loads without a popup.
+void kovlet.ready.then(() => kovlet.session && kovlet.connect().catch(() => {}));
```

## 3. Port queries and writes

A one-table `db.useQuery` becomes `useTable` (or `useQuery`, below). `db.transact` becomes direct writes on the table. Wrap your app in `KovletProvider` once.

```diff title="Todos.tsx"
-import { id, init } from "@instantdb/react";
-import schema from "./instant.schema";
-
-const db = init({ appId: "YOUR_INSTANT_APP_ID", schema });
+import { KovletProvider, useSpace, useSyncStatus, useTable } from "@kovlet/react";
+import { kovlet } from "./kovlet";
 
 export function Todos() {
-  const { isLoading, error, data } = db.useQuery({ todos: {} });
-  if (isLoading) return null;
-  if (error) return <p>{error.message}</p>;
-  const add = (text: string) => db.transact(db.tx.todos[id()].update({ text, done: false, createdAt: Date.now() }));
-  const toggle = (todoId: string, done: boolean) => db.transact(db.tx.todos[todoId].update({ done: !done }));
+  const status = useSyncStatus();
+  const todos = useSpace<typeof kovlet>("main").table("todos");
+  const rows = useTable(todos, { orderBy: "createdAt" });
+  if (status.state === "signed-out") return <button onClick={() => kovlet.connect()}>Connect to Kovlet</button>;
+  const add = (text: string) => todos.insert({ text, done: false, createdAt: new Date() });
+  const toggle = (todoId: string, done: boolean) => todos.update(todoId, { done: !done });
   return (
     <ul>
       <li>
         <button onClick={() => add("New todo")}>Add</button>
       </li>
-      {data.todos.map((todo) => (
+      {rows.map((todo) => (
         <li key={todo.id} onClick={() => toggle(todo.id, todo.done)}>
           {todo.text}
         </li>
       ))}
     </ul>
   );
 }
+
+export const App = () => (
+  <KovletProvider client={kovlet}>
+    <Todos />
+  </KovletProvider>
+);
```

### Nested queries

`db.useQuery` with links becomes `useQuery` over the same tree.

Declare the links as `ref` columns with their target table (`t.ref("users")`). `migrate instantdb` writes them from your InstantDB links.

- A forward link (`author`) is the linked row, or `null`.
- A reverse link (`comments` under `posts`, through `comments.post`) is a list.

```diff title="Feed.tsx"
-import { init } from "@instantdb/react";
-import schema from "./instant.schema";
-
-const db = init({ appId: "YOUR_INSTANT_APP_ID", schema });
+import { createKovletClient, t } from "@kovlet/client";
+import { useQuery, useSpace } from "@kovlet/react";
+
+// In your app these tables live in kovlet.ts.
+export const blog = createKovletClient({
+  appName: "Blog",
+  autoConnect: false,
+  spaces: {
+    main: {
+      tables: {
+        users: { name: t.string() },
+        posts: { title: t.string(), author: t.ref("users"), published: t.boolean(), createdAt: t.datetime().indexed() },
+        comments: { post: t.ref("posts"), author: t.ref("users"), body: t.string() },
+      },
+    },
+  },
+});
 
 export function Feed() {
-  const { isLoading, error, data } = db.useQuery({
-    posts: { $: { where: { published: true }, order: { serverCreatedAt: "desc" }, first: 20 }, author: {}, comments: { author: {} } },
-  });
+  const main = useSpace<typeof blog>("main");
+  const { isLoading, error, data } = useQuery(main, {
+    posts: { $: { where: { published: true }, order: { createdAt: "desc" }, limit: 20 }, author: {}, comments: { author: {} } },
+  });
   if (isLoading) return null;
   if (error) return <p>{error.message}</p>;
   return (
     <ul>
-      {data.posts.map((post) => (
+      {data?.posts.map((post) => (
         <li key={post.id}>
-          {post.title} by {post.author?.name} ({post.comments.length} comments)
+          {post.title} by {post.author?.name} ({post.comments.length} comments)
         </li>
       ))}
     </ul>
   );
 }
```

- InstantDB orders by `serverCreatedAt`. Kovlet orders by a column you declare, such as `createdAt: t.datetime().indexed()`.
- `first: 20` is `limit: 20`. The next page is `after: pageInfo.posts.endCursor`.
- For large spaces, set `sync: "query"` on the slot in `createKovletClient`. The client then holds only the rows your queries cover. `useQuery` subscribes while the component is mounted.

### Writes that must succeed together

Use `space.transact` where InstantDB code passes several entities to one `db.transact`. For example, creating a team together with its first membership.

The writes show up locally at once and sync as one batch. If the server rejects any of them, none of them apply. A taken unique handle is one reason for a rejection.

```ts title="create-team.ts"
import { kovlet } from "./kovlet";

// InstantDB:
// db.transact([
//   db.tx.teams[teamId].update({ name }),
//   db.tx.memberships[id()].update({ role: "owner" }).link({ team: teamId, user: userId }),
// ]);
export async function createTeam(name: string, userId: string) {
  await kovlet.space("main").transact((tx) => {
    const team = tx.table("teams").insert({ name });
    tx.table("memberships").insert({ team: team.id, user: userId, role: "owner" });
  });
}
```

> **Note:** In the SDK, `space.transact` needs a server that speaks sync protocol v2. A protocol v1 connection rolls the batch back with `unsupported_protocol`. Server code can use `POST /v1/spaces/{space}/transact` on any server.

## 4. Move permissions

Kovlet has two kinds of people:

- **End users** sign in to your app itself, like InstantDB's `$users`. Rules decide what they may do.
- **Members** are your team, with Kovlet accounts. They get a role on the whole Data Space and aren't bound by rules.

### End users: rules

`kovlet.perms.json` has the shape of `instant.perms.ts`.

Kovlet is **closed by default**. An end user can't view, create, update or delete in a table until a rule allows it. InstantDB is open by default. So the command writes an explicit `"true"` wherever your app relied on that default, and lists each one in `KOVLET_MIGRATION.md`.

Both use CEL. So the command carries expressions over, and rewrites what the migration renamed:

| InstantDB rule pattern | `kovlet.perms.json` |
| --- | --- |
| Not set (open by default) | `"true"`, listed in the report |
| `true` or `"true"`, `false` or `"false"` | `"true"`, `"false"` |
| Signed-in users: `"auth.id != null"` | `"auth.id != null"` |
| Owner column: `"auth.id == data.creatorId"` | `"auth.id == data.creatorId"` (renamed attributes get their new column names) |
| Owner link: `"auth.id in data.ref('owner.id')"` | `"auth.id in data.ref('ownerId.id')"`: a has-one link label `x` became the ref column `xId` |
| Team membership: `"auth.id in data.ref('team.members.id')"` | The same path through the ref columns, child tables and join tables the migration made, at most 3 links |
| Pinning a field: `"newData.ownerId == data.ownerId"` | the same |
| `bind: ["isOwner", "auth.id == data.ownerId"]` | `bind`, translated the same way |
| `ruleParams.token` | `params.token` |
| `$users` view | `_users` view. Both default to "each user sees their own row". |
| `$files` rules over `data.path` | `_files` rules over `data.path` (and `data.size`) |
| `auth.ref(...)`, `.exists()` and other list macros, `request.*`, `newData.ref(...)` | `"false"`, listed in the report for a hand translation |
| Rules on an entity that became a join table | `"false"`: the join table's columns differ, so write its rule by hand |

Apply the file in one of three ways:

- As an owner in the console: Access → End users → Rules → *Code*, then *Test as an end user*.
- As an owner over REST: `PUT /v1/spaces/{space}/rules` with `{"document": …}`.
- From code: propose it with `POST /v1/spaces/{space}/rules/proposals`, for an owner to approve.

The server checks every rule against the migrated schema. It names any rule it can't compile.

Then turn on end-user sign-in for your app and set up its sign-in methods. See [Let strangers sign in to your app](/docs/end-users).

### Members: roles

Kovlet grants a role on a whole Data Space to people, machines and apps. An app's effective role is the lower of the user's role and the app's grant.

| InstantDB rule | Kovlet access |
| --- | --- |
| `view: "auth.id != null"` | Invite people to the Data Space as Viewer or Editor. |
| `create` and `update` limited to signed-in users | Give those people the Editor role. |
| Per-row owner checks | Members see every row. Per-row rules bind end users only; for members, put private data in its own Data Space. |
| `delete: "false"` | Grant the app Viewer. Deletes by editors go to the Trash and can be restored. |
| Admin token on a server | A Machine Auth Key for that server, created in the console. |

> **Note:** Apps are approved per machine. The first time your app runs on a new device, the user approves it once with a short code.

## 5. Move sign-in

Your users keep their ids and sign in with the same email. Turn on end-user sign-in for the app in the console first. Then port the `db.auth` calls to `kovlet.auth`:

```diff title="Login.tsx"
-import { init } from "@instantdb/react";
-const db = init({ appId: "YOUR_INSTANT_APP_ID" });
+import { useAuth } from "@kovlet/react";
+import { kovlet } from "./kovlet";
 
 export function Login({ email, code }: { email: string; code: string }) {
-  const { user } = db.useAuth();
-  const send = () => db.auth.sendMagicCode({ email });
-  const verify = () => db.auth.signInWithMagicCode({ email, code });
+  const { user } = useAuth();
+  const send = () => kovlet.auth.sendMagicCode({ email });
+  const verify = () => kovlet.auth.signInWithMagicCode({ email, code });
   return user ? <p>Signed in as {user.email}</p> : <button onClick={send}>Email me a code</button>;
 }
```

The [end-users guide](/docs/end-users) covers OAuth, ID tokens, guests, admin access with `Kovlet-As-End-User`, and the REST endpoints.

- **Sync.** While an end user is signed in, `useQuery` / `liveQuery` / `useTable` sync live as them over protocol 2. They hold only the rows the rules allow. Sign-out clears those rows from the device. `kovlet.auth.records(table)` reads once over REST.
- **Not supported:**
  - password and SMS sign-in
  - OAuth clients shared by Kovlet (you register your own with each provider)
  - linking an end user to a Kovlet account. End users and Kovlet accounts are separate on purpose, even with the same email.

## 6. Move data and files (optional)

The command above does this step for you. To do it by hand:

1. Export your InstantDB data to JSON with InstantDB's admin SDK, for example `await db.query({ todos: {} })`.
2. Save it as `instant-export.json`.
3. Run the Node script below. It signs in with a device code and writes every row into your Data Space.
4. Re-upload files with `space.files.upload` the same way.

```sh title="terminal"
KOVLET_SPACE_ID=<your Data Space id> npx tsx import-todos.ts
```

```ts title="import-todos.ts"
import { readFile } from "node:fs/promises";
import { createKovletClient, t } from "@kovlet/client";

type InstantTodo = { id: string; text: string; done: boolean; createdAt: number };

const kovlet = createKovletClient({
  appName: "InstantDB import",
  spaces: {
    main: {
      spaceId: process.env.KOVLET_SPACE_ID,
      tables: { todos: { text: t.string(), done: t.boolean(), createdAt: t.datetime() } },
    },
  },
});

const { todos } = JSON.parse(await readFile("instant-export.json", "utf8")) as { todos: InstantTodo[] };
const table = kovlet.space("main").table("todos");
for (const todo of todos) {
  table.insert({ id: todo.id, text: todo.text, done: todo.done, createdAt: new Date(todo.createdAt) });
}
await kovlet.whenSynced(120_000);
console.log(`Imported ${todos.length} todos`);
kovlet.disconnect();
```

> **You should see**
>
> - `Imported <n> todos`, with `<n>` the number of todos in your export.

> **Caution:** Run this against a copy first. Free workspaces cap the number of rows, so check your plan before importing a large export.

## Check your migration

> **You should see**
>
> - Row counts in the console's Explorer that match your InstantDB export.
> - Two browser windows of your app showing each other's edits live.
> - Only the people and apps you expect under Access.
> - An end user who signs in with their old email and sees only the rows `kovlet.perms.json` allows. Check with *Test as an end user*.

## Next

- [Kovlet per-record rules reference](/docs/rules-reference#from-instantdb): every `instant.perms.ts` construct and its Kovlet form.
- [Let strangers sign in to your app (end users)](/docs/end-users): end-user sign-in, as `db.auth` was.
- [Kovlet vs Supabase, Convex and Airtable](/docs/compare): how Kovlet compares with other backends.
