Migrating · Platform guides
Coming from Convex
Convert Convex schema tables into object types, move handler permission checks onto types and turn query and mutation functions into deployed EdgeQL files.
- In the schema
- —
What you’ll move#
This guide migrates a Convex notes app to Napalm. The existing project defines tables in convex/schema.ts, enforces authorization at the top of each query and mutation function and subscribes to reactive reads in React with useQuery.
| In Convex | In Napalm |
|---|---|
defineTable and v.id(…) | Object types and typed links |
| Auth checks repeated in every function | Declarative access rules written once per type |
| Query functions | Deployed read queries in .edgeql files |
| Mutation functions | Atomic write statements in .edgeql files |
useQuery | useLiveQuery |
| Convex actions | Actions pairing a gatekeeper query with a hosted handler |
ctx.scheduler and crons.ts | Transactional jobs and cron schedules |
| Convex file storage | Typed file records governed by schema access rules |
Clerk or Auth0 via auth.config.ts | The same OIDC provider configured on your project |
Before you start#
Create a project in the console and sign in with the napalm CLI. The biggest shift is where data logic executes. A Convex function runs imperative TypeScript across multiple database reads, whereas a Napalm deployed query compiles into one SQL statement inside PostgreSQL. Most Convex queries and mutations combine a lookup, an access check and a write, which collapse cleanly into one EdgeQL statement and a schema rule. Code that calls third-party APIs stays TypeScript inside a handler.
Turn tables into types#
In Convex, convex/schema.ts defines tables, typed v.id references and explicit lookup indexes for foreign keys and user tokens.
// convex/schema.tsimport { defineSchema, defineTable } from 'convex/server'import { v } from 'convex/values' export default defineSchema({ users: defineTable({ tokenIdentifier: v.string(), email: v.string(), name: v.optional(v.string()), }).index('by_token', ['tokenIdentifier']), notes: defineTable({ ownerId: v.id('users'), sharedWith: v.optional(v.array(v.id('users'))), title: v.string(), body: v.string(), }).index('by_owner', ['ownerId']),})napalm schema draft --from convex/ generates an initial dbschema/default.gel from that file. Translating a Convex schema covers every validator mapping.
Direct Convex translation
The CLI converts Convex tables and document ID validators into linked object types.
Single v.id fields become object links, and arrays of IDs become multi links. Drop manual foreign-key indexes and the by_token user lookup index because Napalm indexes links automatically and resolves caller sessions natively.
type Note { required owner: Person; multi shared_with: Person; required title: str; required body: str; required created: datetime { default := datetime_current(); }; old_id: str { constraint exclusive; }; access policy owner_has_full_access allow all using (.owner.identity ?= global caller); access policy shared_with_can_read allow select using ((global caller in .shared_with.identity) ?? false); access policy the_move_can_write allow all using (global role ?= 'service');}Move function checks into access rules#
In Convex, every query and mutation function looks up the caller and enforces read or write checks in TypeScript before returning rows.
// convex/notes.tsimport { query } from './_generated/server' export const list = query({ args: {}, handler: async (ctx) => { // Every function works out who is asking, and what they may see, for itself. const identity = await ctx.auth.getUserIdentity() if (!identity) return [] const user = await ctx.db .query('users') .withIndex('by_token', (q) => q.eq('tokenIdentifier', identity.tokenIdentifier)) .unique() if (!user) return [] const mine = await ctx.db .query('notes') .withIndex('by_owner', (q) => q.eq('ownerId', user._id)) .collect() const others = await ctx.db.query('notes').collect() return [...mine, ...others.filter((note) => note.sharedWith?.includes(user._id))] },})The first half of convex/notes.ts resolves the current user, and the second half filters which notes that user may read. Every other function touching notes has to repeat both steps. In Napalm, both checks move into two access rules on Note, so the query file only declares the shape to return.
# The notes the caller owns or was given. The rules decide which: the query doesn't say.select Note { id, title, body, created, is_mine := .owner.identity ?= global caller }order by .created desc- Declared once
- Access rules apply across deployed queries, live subscriptions and full-text search, including queries written months later.
- Closed by default
- A Convex function that omits its auth check exposes every document in the table. A Napalm type without an access rule returns zero rows.
- Direct caller identity
ctx.auth.getUserIdentity()becomesglobal caller, bound directly from the verified session token without querying auserstable first.
Turn functions into deployed queries#
Query and mutation functions each become a .edgeql file in dbschema/queries, and function arguments map to typed query parameters.
# A note of the caller's own. Someone with no person yet has no owner to give it, and it's refused.insert Note { owner := assert_exists(assert_single((select Person filter .identity ?= global caller))), title := <str>$title, body := <str>$body,}In React, replace useQuery with useLiveQuery to keep components synchronized as commits arrive:
// src/NoteList.tsximport { deployed } from 'napalm-client'import { useLiveQuery } from 'napalm-client/react' type Note = { id: string; title: string; body: string; created: string; is_mine: boolean } /** Reference the deployed query in dbschema/queries/myNotes.edgeql. */const myNotes = deployed<Note, Record<string, never>>('myNotes') export function NoteList() { // Subscribe to live query results, replacing useQuery(api.notes.list). const { rows } = useLiveQuery(myNotes, {}) return ( <ul> {rows?.map((note) => ( <li key={note.id}>{note.title}</li> ))} </ul> )}Deployed queries and live hooks preserve Convex’s live reactivity while running inside PostgreSQL:
Atomic EdgeQL statements
Reads, permission checks and multi-type writes execute as one compiled SQL statement.
Commit-aligned live hooks
Every active live query on a screen updates together at each commit.
Four details govern how Convex functions translate to EdgeQL and client hooks:
- Reactivity
- Convex reruns a query function whenever its read set changes. In Napalm,
useLiveQuerystreams updated results whenever a commit affects the query and advances every live query on the page to the same commit. - Generated types
napalm generateemits typed functions and React hooks for every query to replaceapi.notes.list. TypeScript shows both.- Optimistic updates
- Components can render pending mutations immediately before commit confirmation. Realtime & collaboration demonstrates optimistic UI state.
- Branching logic
- Functions that read, branch in TypeScript and write become a single EdgeQL statement using
withbindings or conditionalif … elseexpressions. Complex procedural workflows run in a hosted handler.
Import exported documents#
npx convex export writes each table to a JSONL file inside a zip archive. The import script (scripts/from-convex.ts) transforms each JSONL line into the shape expected by your EdgeQL import statements and streams batches through the sender in Switching over.
// scripts/from-convex.tsimport { createReadStream } from 'node:fs'import { createInterface } from 'node:readline'import { move } from './send' /** One table of `npx convex export`, unzipped: a document a line. */async function* table(name: string): AsyncGenerator<Record<string, any>> { const lines = createInterface({ input: createReadStream(`export/${name}/documents.jsonl`) }) for await (const line of lines) if (line.trim()) yield JSON.parse(line)} /** Each document as the import statement reads a row. */async function* shaped<Row extends object>(name: string, shape: (document: Record<string, any>) => Row) { for await (const document of table(name)) yield shape(document)} // People first: a note names its owner. A document's _id is its old id, and _creationTime is in milliseconds.await move( 'importPeople', shaped('users', (user) => ({ id: user._id, email: user.email, name: user.name ?? user.email, // Convex writes who someone is as "issuer|subject". Napalm's rule reads the two with a space between. sign_ins: user.tokenIdentifier ? [user.tokenIdentifier.replace('|', ' ')] : [], })),)await move( 'importNotes', shaped('notes', (note) => ({ id: note._id, owner_id: note.ownerId, shared_with: note.sharedWith ?? [], title: note.title, body: note.body, created_at: new Date(note._creationTime).toISOString(), })),)# Export every Convex table as JSONL files inside a zip archivenpx convex export --path export.zipunzip export.zip -d export npm install tsxNAPALM_URL=https://<project-address>/branches/rehearsal NAPALM_KEY=ndb_… npx tsx scripts/from-convex.tsEach Convex export captures a point-in-time snapshot. At cutover, pause writes in Convex, run one fresh export and re-run scripts/from-convex.ts from the start. Previously imported rows upsert cleanly by old_id.
Migrate auth, files and schedules#
- Sign-in
- Keep your existing Clerk, Auth0 or OIDC provider. Configure the same issuer with
napalm sign-in provider notes oidc(billed as one SSO connection), and eachtokenIdentifierexported by the script maps returning users directly to theirPersonrecord. Moving your users shows the claim query. - Files
- Insert file records storing each temporary URL from
ctx.storage.getUrl, then runnapalm files importso Napalm fetches and verifies the bytes. Files & uploads covers file types. - Actions
- Code calling Stripe, Resend or LLM APIs moves into a handler you host, guarded by a deployed EdgeQL query that selects only caller-authorized records. Actions defines the request contract.
- Scheduled work
ctx.scheduler.runAfterbecomes a transactional job queued in the same commit, andcrons.tsentries becomenapalm schedules addcommands.- Search
- Full-text and vector search indexes become declarative indexes on your object types. Search covers both.
Check the migration#
Run the import script twice against a branch
Both runs print identical counts matching the line counts in your Convex export.
Sign in through your OIDC provider as an imported user
Owned notes and shared notes appear immediately after
claimPersonruns.Add a note in one browser window
A second window signed in as the same user updates live without reloading.
Attempt a write before creating a Person record
For a new user who has no
Personrow yet,addNoteaborts cleanly becauseassert_existsrequires an owningPerson.