tutorial··5 min read·WoWSQL Team

Migrate Firebase to WoWSQL: Firestore Data, Auth Users, Files

Firebase to Postgres on WoWSQL: export Firestore with the Admin SDK, load it with psql or the WoWSQL CLI, map auth users, copy Storage, and the known gaps.

To migrate from Firebase to WoWSQL, export each Firestore collection with the Firebase Admin SDK into CSV (one row per document, with the document ID and its fields as JSON), load the CSV into a Postgres staging table, and copy it into real tables with SQL. Then export your users with firebase auth:export to build an ID mapping, copy Cloud Storage files with gcloud storage cp and an upload script, and rewrite Security Rules as Row Level Security. One gap to plan around: Firebase passwords are hashed with Firebase's modified scrypt, and WoWSQL documents no way to import password hashes, so password users reset their password or sign in with Google or another OAuth provider on their first visit.

This is the hands-on companion to our Firebase to Postgres migration overview and the Firestore data-modelling guide. We tested the export script's conversion code, the CSV load and the SQL transforms on a local PostgreSQL 17 server on 30 November 2026, and checked the WoWSQL CLI commands against wowsql --help (1.7.0). We didn't run anything against a live Firebase or WoWSQL project.

Key facts (checked 30 November 2026)

  • No Firebase importer is documented on WoWSQL. The path is export, load, transform.
  • Auth export: firebase auth:export users.json --format=json exports users with password hashes, using Firebase's modified SCRYPT (Firebase CLI docs). WoWSQL documents no hash import, so the export is for mapping IDs, not for moving passwords.
  • Loading: psql \copy over the WoWSQL direct connection string, or wowsql db import-csv from the WoWSQL CLI (pip install wowsql-cli).
  • Data API is off by default on new WoWSQL projects. Enable it before your app calls REST (Compute docs).
  • Regions: Mumbai, US East and Frankfurt. There's no UK region. Plans: Free $0, Pro $25/month, Scale $99/month (pricing).

Firebase to WoWSQL mapping

Firebase WoWSQL (Postgres) How
Firestore collection Table Admin SDK export, then CSV, staging, insert … select
Document ID text primary key Keep it, so references still resolve
Map / nested object jsonb column, or a child table Decide per field
Array text[], jsonb, or a join table Join table if you query by element
Subcollection Child table with a foreign key Export with a collection group query
Timestamp timestamptz The script writes ISO 8601 strings
GeoPoint Two double precision columns The script writes {lat, lng}
DocumentReference text holding the document path or ID The script writes the path
Security Rules RLS policies with auth.uid() Rewrite by hand (RLS guide)
Firebase Auth users WoWSQL Auth users Users sign in again; map IDs
Cloud Storage WoWSQL Storage buckets gcloud storage cp, then upload script
onSnapshot listeners WoWSQL Realtime Enable each table
Cloud Functions WoWSQL Compute (Node.js or Python) Rewrite

Step 1: Create the project and install the tools

Create a WoWSQL project in the dashboard (pick Mumbai, US East or Frankfurt), enable Authentication, and copy the direct connection string, anon key and service role key from the Connect menu and Project Settings. Then:

pip install wowsql-cli
wowsql login
wowsql projects set-default your-project-slug

npm install firebase-admin @wowsql/sdk@3.10.0
export WOWSQL_DB_URL='postgresql://USER:[PASSWORD]@db.your-project-slug.wowsqlconnect.com:5432/postgres'

Create a Firebase service account key (Project settings → Service accounts) and point GOOGLE_APPLICATION_CREDENTIALS at it.

Step 2: Export Firestore collections to CSV

This script pages through each collection by document ID, converts Firestore types to plain JSON, and writes id,data CSV files:

// export-firestore.mjs
// GOOGLE_APPLICATION_CREDENTIALS=./service-account.json node export-firestore.mjs users posts
import { initializeApp, applicationDefault } from 'firebase-admin/app'
import { getFirestore, Timestamp, GeoPoint, DocumentReference, FieldPath } from 'firebase-admin/firestore'
import { createWriteStream } from 'node:fs'

initializeApp({ credential: applicationDefault() })
const db = getFirestore()

function toPlain(value) {
  if (value === null || value === undefined) return null
  if (value instanceof Timestamp) return value.toDate().toISOString()
  if (value instanceof GeoPoint) return { lat: value.latitude, lng: value.longitude }
  if (value instanceof DocumentReference) return value.path
  if (Buffer.isBuffer(value)) return value.toString('base64')
  if (Array.isArray(value)) return value.map(toPlain)
  if (typeof value === 'object') {
    return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, toPlain(v)]))
  }
  return value
}

const csvField = (s) => '"' + String(s).replaceAll('"', '""') + '"'

async function exportCollection(name) {
  const out = createWriteStream(`${name}.csv`)
  out.write('id,data\n')
  let last = null
  let total = 0
  while (true) {
    let q = db.collection(name).orderBy(FieldPath.documentId()).limit(500)
    if (last) q = q.startAfter(last)
    const snap = await q.get()
    if (snap.empty) break
    for (const doc of snap.docs) {
      out.write(`${csvField(doc.id)},${csvField(JSON.stringify(toPlain(doc.data())))}\n`)
    }
    total += snap.size
    last = snap.docs[snap.docs.length - 1]
  }
  out.end()
  console.log(`${name}: ${total} documents -> ${name}.csv`)
}

for (const c of process.argv.slice(2)) await exportCollection(c)

Each read counts toward your Firestore bill. For subcollections, adapt the loop to db.collectionGroup('comments') and save doc.ref.parent.parent.id as the parent ID column.

Step 3: Load the CSV into a staging table

Staging tables go in a schema outside public, so the Data API never exposes them:

create schema if not exists staging;
create table staging.posts_raw (id text primary key, data jsonb not null);
psql "$WOWSQL_DB_URL" -c "\copy staging.posts_raw (id, data) from 'posts.csv' with (format csv, header true)"

If you can't reach port 5432, flatten the CSV to plain columns first and load it with the CLI. wowsql db import-csv inserts into an existing table, or creates one with all-text columns when you pass --create-table:

wowsql db import-csv ./posts_flat.csv --table posts_import --create-table
wowsql db import-csv ./posts_flat.csv --table posts --on-conflict ignore

We couldn't run import-csv against a live project, so check the row counts afterwards with wowsql db query "select count(*) from posts".

Step 4: Transform staging rows into real tables

Design the target table (the data-modelling guide goes deeper), then cast fields out of jsonb:

create table public.posts (
  id          text primary key,           -- Firestore document id
  author_id   text,                        -- Firebase UID for now; re-mapped in Step 6
  title       text not null,
  tags        text[] not null default '{}',
  lat         double precision,
  lng         double precision,
  created_at  timestamptz
);

insert into public.posts (id, author_id, title, tags, lat, lng, created_at)
select id,
       data->>'authorId',
       data->>'title',
       coalesce(array(select jsonb_array_elements_text(data->'tags')), '{}'),
       (data->'loc'->>'lat')::double precision,
       (data->'loc'->>'lng')::double precision,
       (data->>'createdAt')::timestamptz
from staging.posts_raw;

-- every staged document landed?
select (select count(*) from staging.posts_raw) as staged,
       (select count(*) from public.posts)      as loaded;

Documents in one collection often have different fields. Query select distinct jsonb_object_keys(data) from staging.posts_raw; before you design columns, so you don't drop a field that only some documents have.

Step 5: Rewrite Security Rules as RLS

A rule like allow update: if request.auth.uid == resource.data.authorId becomes:

alter table public.posts enable row level security;

create policy "anyone can read posts" on public.posts
  for select using (true);

create policy "authors update their posts" on public.posts
  for update using (auth.uid()::text = author_id) with check (auth.uid()::text = author_id);

WoWSQL user IDs are UUIDs, and author_id holds Firebase UIDs until Step 6 re-maps them. These policies only match after that. If you want a uuid column instead, add it during re-mapping and switch the policies over.

Step 6: Move auth users (what works, what doesn't)

Export the users:

firebase auth:export users.json --format=json --project your-firebase-project-id

The file includes localId (the UID), email, phone, provider info and, for password users, passwordHash and salt. Firebase's own docs say most projects hash with a modified scrypt that needs the project's signer key to verify. WoWSQL documents no way to import hashes in any format, so you can't move passwords. What you can do:

  • Google, Apple, GitHub and other OAuth users sign in with the same provider on WoWSQL (19 providers work today, OAuth docs). Their WoWSQL user ID is new.
  • Email/password users create a password again through sign-up or the reset flow (forgotPassword / resetPassword in the SDK).
  • Phone users sign in with WoWSQL phone OTP, using your own Twilio, Fast2SMS or MSG91 account.

Build the mapping table from the export:

jq -r '.users[] | [.localId, (.email // ""), (.phoneNumber // ""), ([.providerUserInfo[]?.providerId] | join(" "))] | @csv' users.json > legacy_users.csv
create table staging.legacy_users (old_uid text primary key, email text, phone text, providers text, new_id uuid);
psql "$WOWSQL_DB_URL" -c "\copy staging.legacy_users (old_uid, email, phone, providers) from 'legacy_users.csv' with (format csv)"

When a user signs in for the first time, a server route verifies their token with ProjectAuthClient.getUser(accessToken), sets new_id where the verified email matches, and updates author_id and other user columns. The Supabase guide has the full claim function. Firebase UIDs are 28-character strings, not UUIDs, so keep old_uid as text.

Step 7: Copy Cloud Storage files

Download the bucket, then upload the folder into a WoWSQL bucket while keeping paths:

gcloud storage cp -r gs://your-project.appspot.com ./firebase-storage

Your bucket may be named your-project.firebasestorage.app. Check the Firebase console.

// upload-folder.mjs
// WOWSQL_PROJECT_URL=https://your-project-slug.wowsqlconnect.com WOWSQL_SERVICE_KEY=... node upload-folder.mjs ./firebase-storage avatars
import { WowSQLStorage } from '@wowsql/sdk'
import { readdir } from 'node:fs/promises'
import { join, relative, sep } from 'node:path'

const [root, bucket] = process.argv.slice(2)
const storage = new WowSQLStorage({
  projectUrl: process.env.WOWSQL_PROJECT_URL,
  apiKey: process.env.WOWSQL_SERVICE_KEY, // server-side only
})

async function* walk(dir) {
  for (const entry of await readdir(dir, { withFileTypes: true })) {
    const full = join(dir, entry.name)
    if (entry.isDirectory()) yield* walk(full)
    else yield full
  }
}

let count = 0
for await (const file of walk(root)) {
  const key = relative(root, file).split(sep).join('/') // users/u1/avatar.png
  await storage.uploadFromPath(file, bucket, key)
  count++
  console.log('uploaded', `${bucket}/${key}`)
}
console.log(`${count} files uploaded`)

Create the bucket first in the dashboard, or with storage.createBucket('avatars', { public: true }). Against a mock server, SDK 3.10.0 sent users/u1/avatar.png as folder users/u1 with file name avatar.png. Then rewrite stored download URLs with an SQL replace() to https://your-project-slug.wowsqlconnect.com/storage/v1/object/public/{bucket}/{path} for public buckets. Firebase download tokens have no equivalent, and the storage docs say presigned URLs aren't available, so serve private files through a server route.

Step 8: Replace listeners and Cloud Functions

  • onSnapshot: enable each table for realtime with POST /realtime/v1/enable, then subscribe with client.realtime.channel('posts').on('postgres_changes', { event: '*', schema: 'public', table: 'posts' }, cb).subscribe() (realtime docs). Test tables with RLS on a scratch project first.
  • Cloud Functions: rewrite as WoWSQL Compute handlers in Node.js or Python. Each function is one file with no package installs, and secrets come from wowsql secrets set KEY "value" (Compute docs). Firestore triggers become database triggers or a function your app calls.
  • Client code: replace Firestore calls with @wowsql/sdk (import { WowSQLClient } from '@wowsql/sdk', then client.table('posts').select('*').eq('author_id', id).get()). The SDK is CommonJS, so use require or named imports.

Step 9: Enable the Data API and cut over

Enable the Data API for the project and expose the tables your app calls, or REST returns 403 DATA_API_DISABLED. Then follow the migration runbook: freeze writes in Firebase (for example, temporary Security Rules that deny writes), run the export again, reload, verify counts and switch the app.

What doesn't move from Firebase

Item Why What to do
Passwords Modified-scrypt hashes; WoWSQL documents no hash import Reset flow or OAuth
Sessions and ID tokens Signed by Firebase Users sign in once
Offline persistence in the client SDK Postgres REST has no offline cache Cache in your app if you need it
Download tokens and signed URLs No presigned URLs per WoWSQL storage docs Public bucket or server route
Analytics, Crashlytics, FCM, Remote Config Not database features Keep them in Firebase; they work alongside WoWSQL

FAQ

How do I migrate from Firebase to Postgres?

Export each Firestore collection with the Admin SDK to CSV or JSON, load it into a staging table with psql \copy, and insert it into typed tables with SQL. Rewrite Security Rules as RLS policies, map Firebase UIDs to new user IDs, and copy Cloud Storage files with gcloud storage cp and an upload script.

Can I import Firebase Auth users into WoWSQL with their passwords?

No. firebase auth:export gives you password hashes in Firebase's modified scrypt format, but WoWSQL documents no way to import password hashes. Use the export to build an ID mapping, then have users reset their password or sign in with the same OAuth provider.

Does WoWSQL have a Firestore import tool?

No Firestore importer is documented. Use the Admin SDK export script in this guide, then psql \copy or wowsql db import-csv to load the data.

How do Firestore subcollections map to Postgres?

Each subcollection becomes a child table with a foreign key to the parent table. Export it with a collection group query and keep the parent document ID as a column.

What replaces Firestore realtime listeners on WoWSQL?

WoWSQL Realtime sends INSERT, UPDATE and DELETE events over a WebSocket. Enable each table with POST /realtime/v1/enable, then subscribe with client.realtime.channel(...).on('postgres_changes', ...).

Is Firebase cheaper than WoWSQL?

It depends on your reads and writes. Firebase Blaze bills per document operation, while WoWSQL plans are flat: Free $0, Pro $25/month, Scale $99/month, plus listed overages. See our Firebase pricing explainer for worked examples.

Related guides

Create a free WoWSQL project and load one collection into it as a trial. · Pricing · CLI docs