Migrating · Platform guides
Coming from Firebase
Add static types and links to Firestore collections, translate security rules into schema policies and migrate Firebase Auth accounts.
- In the schema
ext::files::File
What you’ll move#
This guide migrates a Firebase notes app to Napalm. The existing project stores documents in a Firestore notes collection, enforces read and write permissions in firestore.rules, subscribes to updates through onSnapshot listeners and manages users in Firebase Authentication.
| In Firebase | In Napalm |
|---|---|
| Firestore document collections | Declared object types with typed properties |
| Stored document IDs and subcollections | Direct links and multi links between objects |
| Denormalized fields copied to avoid extra reads | Single-query reads across object links |
firestore.rules | Access rules declared on each type |
| Client queries forced to mirror security rules | Clean queries filtered automatically by access rules |
onSnapshot listeners | Live queries over deployed EdgeQL reads |
| Callable and triggered Cloud Functions | Deployed queries, actions and background jobs |
| Firebase Authentication | Built-in project sign-in |
Cloud Storage and storage.rules | Typed file records governed by schema access rules |
Before you start#
Create a project in the console, sign in with the napalm CLI and generate a service account key for your Firebase project. The biggest shift is adopting a strict schema. Sample a few hundred documents from each Firestore collection before writing dbschema/default.gel so occasionally omitted fields become optional properties and mixed-type fields settle on a single type.
Turn collections into types#
In Firestore, documents store untyped fields, string IDs pointing to other collections and denormalized copies such as ownerName to avoid extra client reads.
// notes/8fK2… (one document in the notes collection){ "ownerId": "Xq3…", "ownerName": "Ada", "sharedWith": ["b7T…", "m0P…"], "title": "Plan", "body": "…", "createdAt": Timestamp}In Napalm, each collection becomes a declared object type in dbschema/default.gel with validated properties and typed links.
Typed schema validation
Declared types and links replace untyped collections, subcollections and denormalized copies.
The ownerId string becomes a typed link to Person, and the sharedWith array becomes a multi link. Drop the denormalized ownerName copy because EdgeQL queries read .owner.name directly without extra round trips or stale data.
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');}- Subcollections
- A
commentssubcollection under each note becomes aCommenttype with a requirednotelink. One query fetches a note alongside all of its comments. - Maps and arrays
- Maps with fixed keys become properties or linked types, arbitrary-key maps map to
json, and scalar arrays become typed arrays such asarray<str>. - Counters
- Counts previously maintained by Cloud Function triggers become computed properties such as
comment_count := count(.<note[is Comment]). - Document IDs
- Napalm assigns each imported object a UUID
idand stores the original Firestore document ID inold_idduring migration.
Convert security rules into access rules#
In Firebase, firestore.rules compares request.auth.uid against fields on each document across separate read, create, update and delete clauses.
rules_version = '2';service cloud.firestore { match /databases/{database}/documents { match /notes/{note} { allow read: if request.auth != null && (resource.data.ownerId == request.auth.uid || request.auth.uid in resource.data.sharedWith); allow create: if request.auth != null && request.resource.data.ownerId == request.auth.uid; allow update, delete: if request.auth != null && resource.data.ownerId == request.auth.uid; } }}Those three Firestore allow statements become the two access rules on Note above: owners have full access, and shared collaborators can read. Beyond syntax, Napalm rules evaluate across your object graph.
- Graph traversal
- Firestore rules inspect one document at a time and bill an extra document read for every
get()lookup. Napalm access rules traverse links to any depth inside one SQL statement. - Rules act as filters
- Firestore rejects any query whose filter is broader than your security rules. In Napalm, a query selects
Notewith no manual filter and receives only the rows the caller is allowed to read. - Schema validation
- Field checks written against
request.resource.databecome required properties, scalar types and constraints enforced across every caller, including backend services. - No Admin SDK bypass
- Firebase’s Admin SDK bypasses
firestore.rulesentirely. Napalm service keys receive only the permissions granted to their role in your schema.
Convert snapshot listeners into live queries#
Each Firestore read or listener becomes a named .edgeql file in dbschema/queries. Listing a user’s notes requires neither an owner equality filter nor an array-contains check.
# 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 descClients subscribe to that deployed query over Server-Sent Events and receive rule-filtered updates whenever a commit affects the result set.
Automatic query filtering
Access rules filter every query result without repeating conditions in client code.
Live query subscriptions
Client hooks stream joined, filtered updates together at each database commit.
Four query patterns change when moving from Firestore’s client SDK:
- onSnapshot
useLiveQuerykeeps a deployed query’s result set current in real time. Realtime & collaboration walks through building collaborative views withuseLiveQuery.- Single-trip joins
- A single query fetches a note alongside its author’s name and comments in one request instead of issuing N+1 document reads.
- Atomic multi-type writes
- One EdgeQL statement inserts and updates across multiple types atomically without client-side transaction retry loops.
- Offline writes
- Firestore’s client SDK queues mutations while offline. In Napalm, commits require network connectivity, so offline-capable apps pair a local SQLite or IndexedDB cache with an idempotent outbox. Offline caches & reconnect sync covers that architecture.
Import documents and accounts#
The export script (scripts/from-firebase.ts) lists accounts through the Firebase Admin SDK, pages through each Firestore collection in document-ID order and passes batches to the sender in Switching over.
// scripts/from-firebase.tsimport { cert, initializeApp } from 'firebase-admin/app'import { getAuth } from 'firebase-admin/auth'import { FieldPath, getFirestore, type DocumentData } from 'firebase-admin/firestore'import { move } from './send' initializeApp({ credential: cert(JSON.parse(process.env.FIREBASE_SERVICE_ACCOUNT as string)) }) /** The issuer Napalm records for the providers Firebase calls by these names. */const ISSUERS: Record<string, string> = { 'google.com': 'https://accounts.google.com', 'github.com': 'https://github.com',} /** Everyone in Firebase Authentication with an address or a provider's account, a thousand at a time. */async function* people() { let pageToken: string | undefined do { const page = await getAuth().listUsers(1000, pageToken) for (const user of page.users) { const signIns = user.providerData .filter((provider) => provider.providerId in ISSUERS) .map((provider) => `${ISSUERS[provider.providerId]} ${provider.uid}`) // Someone with neither, such as a phone number alone, has nothing to claim their person by. if (!user.email && signIns.length === 0) continue yield { id: user.uid, email: user.email ?? null, name: user.displayName ?? user.email ?? user.uid, sign_ins: signIns } } pageToken = page.pageToken } while (pageToken)} /** A collection's documents in the order of their ids, five hundred at a time. */async function* documents(collection: string): AsyncGenerator<{ id: string; data: DocumentData }> { let after = '' for (;;) { let page = getFirestore().collection(collection).orderBy(FieldPath.documentId()).limit(500) if (after) page = page.startAfter(after) const found = await page.get() if (found.empty) return for (const document of found.docs) yield { id: document.id, data: document.data() } after = found.docs[found.docs.length - 1].id }} /** Each note as the import statement reads a row. A Timestamp becomes its ISO text. */async function* notes() { for await (const { id, data } of documents('notes')) { yield { id, owner_id: data.ownerId, shared_with: data.sharedWith ?? [], title: data.title, body: data.body, created_at: data.createdAt.toDate().toISOString(), } }} // People first: a note names its owner.await move('importPeople', people())await move('importNotes', notes())npm install firebase-admin tsxFIREBASE_SERVICE_ACCOUNT="$(cat service-account.json)" \NAPALM_URL=https://<project-address>/branches/rehearsal NAPALM_KEY=ndb_… \ npx tsx scripts/from-firebase.ts- Google and GitHub
- Each account’s
providerDataentry holds the upstream OAuth subject ID. Returning users sign in with the same Google or GitHub account and immediately see their imported notes. - Email passwords
- Firebase scrypt password hashes stay behind. Password users sign in with an emailed verification code or set a verified new password.
- Phone and anonymous users
- Napalm does not support SMS or anonymous sign-in, so the export script skips accounts that have neither an email address nor a supported OAuth provider.
Moving your users provides the claimPerson query that links returning users to their imported Person records.
Migrate Cloud Functions and Storage#
- Callable functions
- Callable functions that only read or mutated Firestore documents become deployed queries. Functions that call external APIs with secrets become actions that pair a gatekeeper EdgeQL query with a handler you host.
- Firestore triggers
- Post-write Cloud Function triggers become jobs queued in the same commit or signed webhooks delivered after commit.
- Scheduled functions
napalm schedules addruns a deployed query on a cron schedule.- Cloud Storage
- Files become
ext::files::Filerecords linked to their parent object and governed by its access rules. Using a Google Cloud Storage interoperability HMAC key,napalm files store importcopies objects directly over S3. - Messaging, Analytics and Remote Config
- Continue running Firebase Cloud Messaging, Google Analytics and Remote Config alongside your Napalm project.
# Create an interoperability HMAC key in Cloud Storage settings, then preview counts and sample objectsexport NAPALM_SOURCE_SECRET_ACCESS_KEY=…napalm files store import notes --endpoint https://storage.googleapis.com --access-key-id GOOG… \ --map type=default::Attachment,key=old_key,bucket=<your-bucket> --planCheck the migration#
Run the export script twice against a branch
Both runs print identical counts matching your Firestore collections.
Sign in with Google as an imported user
Both owned notes and shared notes appear immediately.
Query all notes as a new user
Napalm executes
myNotescleanly and returns zero rows because no access rule grants that caller read access.Insert a shared note in one browser window
The new note streams live into a collaborator’s window and never appears in an unrelated user’s window.