Migrating · Platform guides
Coming from Firebase
Give your Firestore collections a schema, turn security rules into access rules and bring Firebase Authentication’s accounts over.
- In the schema
ext::files::File
What you’ll move#
A notes app on Firebase: a notes collection in Firestore, security rules that control read access to each document, listeners that keep screens current and accounts in Firebase Authentication.
| In Firebase | In Napalm |
|---|---|
| A collection of documents | A type that declares every object’s properties |
| An id stored in a field, or a subcollection | A link to the other object |
| A value copied onto a document to avoid a second read | A read through the link in the same query |
firestore.rules | Access rules on each type |
| A query that has to match the security rule | A query with no access conditions. The rule filters the results |
onSnapshot | A live query on a deployed read |
| Callable and triggered Cloud Functions | Deployed queries, actions and jobs |
| Firebase Authentication | The project’s sign-in |
Cloud Storage and storage.rules | A file type under the record’s rules |
Before you start#
You need a project created in the console, the napalm CLI signed in and a service account key for your Firebase project. The biggest shift is that your data gets a schema. Sample a few hundred documents from each collection before writing the schema: fields that are occasionally missing become optional properties, and any field holding mixed types must settle on one type.
Turn collections into types#
Each Firestore collection becomes a declared type in dbschema/default.gel, turning loose document fields and subcollections into typed properties and links.
Strict types replace untyped collections
Collections, subcollections and denormalized copies become typed links and computed properties checked on every write.
// notes/8fK2… (one document in the notes collection){ "ownerId": "Xq3…", "ownerName": "Ada", "sharedWith": ["b7T…", "m0P…"], "title": "Plan", "body": "…", "createdAt": Timestamp}The owner’s id becomes a link to a person, and the array of ids becomes a link to many. Drop the copied name, because queries read the owner’s name directly through the link without risking stale copies.
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 required link to the note. One query reads the note and its comments together. - Maps and arrays
- A map with known keys becomes properties or a separate type, while an arbitrary-key map stays as
json. An array of values becomes a typed array such asarray<str>. - Counters
- A count maintained by a Cloud Function becomes a computed property, such as
comment_count := count(.<note[is Comment]). - Ids
- Every object gets a new id while keeping the document id in
old_iduntil the move finishes.
Turn security rules into access rules#
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; } }}The three allow statements become the two rules on Note above: an owner may do anything, and people on the share list may read. The deeper difference is graph traversal.
- Rules follow links
- A Firestore rule inspects one document and bills a read for every lookup. A Napalm access rule follows links to any depth, such as team members on a note’s parent project.
- Rules are filters
- Firestore rejects any query that could return a forbidden document, forcing every query to mirror the rule. In Napalm, a query asks for notes and returns only the ones the caller may read.
- Validation
- Checks on
request.resource.databecome required properties, types and constraints in the schema, enforced for every writer including your backend. - The Admin SDK
- The Admin SDK bypasses security rules completely. A Napalm service key receives only the access a rule grants its role.
Turn listeners and reads into queries#
Each read becomes a file in dbschema/queries, deployed by name. The query listing a person’s notes needs no where clause for the owner and no array-contains filter.
Rules filter queries automatically
Queries never repeat security conditions because Napalm filters every read through the type’s rules.
Live queries replace onSnapshot listeners
useLiveQuery keeps joined, filtered results current in lockstep across every commit.
# 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- onSnapshot
useLiveQuerykeeps that query’s result current. Realtime & collaboration builds a shared screen withuseLiveQuery.- Joins
- One query selects a note with its owner’s name and comments in a single request instead of a read per document.
- Batches and transactions
- One statement inserts and updates several types and commits whole or not at all, with no client-side transaction retry loop.
- Offline writes
- Firestore’s client queues writes offline. In Napalm a commit requires the network, so apps that run without signal pair a local SQLite or IndexedDB mirror with an idempotent reconnect outbox. Offline caches & reconnect sync builds that pattern.
Move the documents and the accounts#
The reader lists accounts through the Admin SDK, pages through each collection by document id and hands rows to the sender from 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
providerDataholds the provider’s own id. The same account signs the person straight in to Napalm with their notes waiting. - Passwords
- Firebase password hashes stay behind. People sign in with a one-time code sent to their email address.
- Phone and anonymous
- Napalm has neither. The reader skips any account with no email address and no provider.
Moving your users has the claim query that links each person’s rows at first sign-in.
Move functions, files and other Firebase services#
- Callable functions
- A function that only read or wrote data becomes a deployed query. A function holding a secret becomes an action: a deployed query selects only the records the caller may access, and a handler you host does the external work.
- Firestore triggers
- Work triggered by a write becomes a job queued in the same commit, or a webhook delivered after commit.
- Scheduled functions
napalm schedules addputs a deployed query on a clock.- Cloud Storage
- A file becomes a record linked to the owning object and inherits its read permissions. With an HMAC key, Cloud Storage is S3-compatible so Napalm copies the bytes directly.
- Messaging, Analytics and Remote Config
- Keep using Messaging, Analytics and Remote Config in Firebase alongside your Napalm database.
# An HMAC key for a service account, from Cloud Storage's Interoperability settings. Count and sample first.export 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 move#
Run the reader twice against a branch
Both runs print identical counts, matching your Firestore collections.
Sign in with Google as a moved person
Both their own notes and the notes shared with them appear immediately.
Ask for every note as someone new
Napalm runs the query and returns zero rows because no rule lets that caller read a note.
Add a note in one window
The note appears live in a second window signed in as someone on its share list, and never appears in a third.