What you'll build
- Your Supabase Postgres data imported, or your Firestore data remodeled into Postgres tables
- Your storage files copied into an S3-compatible bucket with a re-runnable script
- Existing users moved to the new auth on their next sign-in, with no forced password reset
- Client SDK calls replaced with Server Components and Server Actions
- A cutover checklist you can follow on the day
Before you start
- A Next.js 16 app (App Router) that uses Supabase or Firebase today
- Admin access to your Supabase or Firebase project
- Node.js 20 or newer, and comfort running scripts with
npx tsx - A CloudHike.dev account with Postgres, Auth and Storage deployed
What moves, and how
A migration is easier when you know up front which parts are a copy and which parts are a rewrite. Here is the honest picture.
| Piece | From Supabase | From Firebase |
|---|---|---|
| Database | Copied by Import database: tables, data, views, functions, types, sequences and indexes | Firestore is a document store, so you design tables and load the data with a script |
| Files | Copied with a script over Supabase's S3-compatible endpoint | Copied with a script using the Firebase Admin SDK |
| Users | Not copied. Moved one by one when they next sign in | Not copied. Moved one by one when they next sign in |
| Access rules | Row-level security policies are not copied. Checks move into server code | Security rules don't apply to Postgres. Checks move into server code |
| Client SDK calls | supabase-js calls become server code | Firebase JS SDK calls become server code |
| Functions | Edge functions are not copied. Rewrite them as route handlers | Rewrite Cloud Functions as route handlers or background jobs |
| Realtime | No realtime service is listed in the CloudHike docs. Poll or refresh instead, or keep it for now | Same for onSnapshot listeners |
Work in this order: copy the data into a development environment, rewrite and test the app against it, then repeat the copy for real on cutover day. Every script below is safe to run more than once for exactly this reason.
Not sure the move is right for you? The Supabase alternative and Firebase alternative pages compare plans side by side, including the cases where staying put is the better choice.
Step 1a: Import your Supabase database
Your Supabase database is plain Postgres, so CloudHike can copy it for you. The import does not bring auth.users, so first copy the user ids and emails into a normal table. You'll need them in Step 3 to link old users to their new accounts.
drop table if exists public.legacy_users;
create table public.legacy_users as
select id, email, created_at
from auth.users;
-- Foreign keys that point at auth.users. auth.users stays behind,
-- so plan to point these at legacy_users after the import.
select conrelid::regclass as table_name, conname as constraint_name
from pg_constraint
where contype = 'f' and confrelid = 'auth.users'::regclass;- In Supabase, open Connect and copy the Session pooler connection string (
*.pooler.supabase.com, port 5432). The direct host is IPv6-only on most plans, and the transaction pooler (port 6543) can't be dumped. - In CloudHike, open your Postgres card, click Open database, then Import database on the Data or Backups tab.
- Paste the connection string. It is used once and never stored, and a read-only user is enough.
- Pick the schemas to copy:
publicand any of your own. Leave out Supabase's own schemas such asauthandstorage. - Check what will be copied, then confirm.
The import replaces all current data in the CloudHike database. A backup is taken first, so you can undo it from the Backups tab ("Before import"). Row-level security policies, owners and grants are not copied. See Import from another database.
After the import, give legacy_users a primary key and a column for the new user id, and point your old foreign keys at it:
alter table legacy_users add primary key (id);
alter table legacy_users add column cloudhike_user_id text unique;
-- One line per constraint from the list above, for example:
alter table profiles
add constraint profiles_id_fkey foreign key (id) references legacy_users (id);Then compare row counts. Run this on both sides and check the numbers match:
select table_name,
(xpath('/row/c/text()', query_to_xml(
format('select count(*) as c from %I.%I', table_schema, table_name), false, true, '')))[1]::text::bigint as row_count
from information_schema.tables
where table_schema = 'public' and table_type = 'BASE TABLE'
order by table_name;Prefer the command line? pg_dump works too. Restore through DIRECT_URL, since the pooled DATABASE_URL is not meant for dumps and restores:
pg_dump --no-owner --no-acl --schema=public "$SUPABASE_DB_URL" | psql "$DIRECT_URL"If your migrations grant rights to anon, authenticated or service_role, a Pro database can create those roles with Add Supabase roles under Open database → Configuration → Roles. See Roles.
Step 1b: Move Firestore data into Postgres
There is no one-click path from Firestore to Postgres, and that's not a tooling gap: a document store and a relational database model data differently. The work is deciding what each collection becomes. These rules of thumb cover most apps:
| In Firestore | In Postgres |
|---|---|
| A collection | A table |
| A document id | A firebase_id text column with a unique index, next to a new numeric id |
A subcollection, such as posts/{id}/comments | A child table with a foreign key to the parent |
| A reference field | A foreign key |
| A map you query by | Its own columns |
| A map you only read whole | A jsonb column |
| An array of strings | A text[] column, or a join table if you query it a lot |
| A Timestamp | A timestamptz column |
Here is an example with users, posts and a comments subcollection. Keep a jsonb column for leftover fields, so nothing is lost while you decide where it belongs.
create table users (
id bigint generated always as identity primary key,
firebase_id text not null unique,
email text,
name text,
plan text not null default 'free',
created_at timestamptz not null default now(),
extra jsonb not null default '{}'
);
create table posts (
id bigint generated always as identity primary key,
firebase_id text not null unique,
user_id bigint references users (id),
title text not null,
body text not null default '',
tags text[] not null default '{}',
published_at timestamptz
);
create table comments (
id bigint generated always as identity primary key,
firebase_id text not null,
post_id bigint not null references posts (id) on delete cascade,
user_id bigint references users (id),
text text not null,
created_at timestamptz not null default now(),
unique (post_id, firebase_id)
);
create index on posts (user_id);
create index on comments (post_id);
-- For Step 3: Firebase Auth users, by uid.
create table legacy_users (
id text primary key,
email text,
cloudhike_user_id text unique
);Export with the Admin SDK. Download a service account key from Firebase console → Project settings → Service accounts, and point GOOGLE_APPLICATION_CREDENTIALS at it. Never commit that file.
npm install -D tsx firebase-admin pg @types/pgimport { applicationDefault, initializeApp } from "firebase-admin/app";
import {
DocumentReference,
FieldPath,
GeoPoint,
getFirestore,
Timestamp,
type Query,
type QueryDocumentSnapshot,
} from "firebase-admin/firestore";
import { appendFile, mkdir, writeFile } from "node:fs/promises";
initializeApp({ credential: applicationDefault() });
const db = getFirestore();
// Turn Firestore types into plain JSON.
function plain(value: unknown): unknown {
if (value instanceof Timestamp) return value.toDate().toISOString();
if (value instanceof DocumentReference) return value.path;
if (value instanceof GeoPoint) return { lat: value.latitude, lng: value.longitude };
if (Array.isArray(value)) return value.map(plain);
if (value && typeof value === "object") {
return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, plain(v)]));
}
return value;
}
// Write one JSON line per document, 500 documents at a time.
async function exportQuery(name: string, query: Query) {
const file = `export/${name}.ndjson`;
await writeFile(file, "");
let last: QueryDocumentSnapshot | undefined;
let count = 0;
for (;;) {
let page = query.orderBy(FieldPath.documentId()).limit(500);
if (last) page = page.startAfter(last);
const snap = await page.get();
if (snap.empty) break;
const lines = snap.docs.map((doc) =>
JSON.stringify({ id: doc.id, parentId: doc.ref.parent.parent?.id ?? null, data: plain(doc.data()) }),
);
await appendFile(file, lines.join("\n") + "\n");
count += snap.size;
last = snap.docs[snap.docs.length - 1];
}
console.log(`${name}: ${count} documents`);
}
async function main() {
await mkdir("export", { recursive: true });
await exportQuery("users", db.collection("users"));
await exportQuery("posts", db.collection("posts"));
await exportQuery("comments", db.collectionGroup("comments")); // posts/{postId}/comments
}
main().catch((err) => {
console.error(err);
process.exit(1);
});Export your Firebase Auth users too, so you can link them in Step 3. The Firebase CLI does this:
npx firebase-tools auth:export auth-users.json --format=json --project your-firebase-project-idauth-users.json contains password hashes. You don't need them for this migration, but treat the file as a secret and delete it when you are done.
Now load everything. Each insert is an upsert keyed on firebase_id, so you can run the script again on cutover day to pick up changes.
import { createReadStream } from "node:fs";
import { readFile } from "node:fs/promises";
import { createInterface } from "node:readline";
import { Pool } from "pg";
const pool = new Pool({ connectionString: process.env.DATABASE_URL, max: 3 });
type Line<T> = { id: string; parentId: string | null; data: T };
type UserDoc = { email?: string; displayName?: string; plan?: string; createdAt?: string; [k: string]: unknown };
type PostDoc = { authorId?: string; title?: string; body?: string; tags?: string[]; publishedAt?: string };
type CommentDoc = { authorId?: string; text?: string; createdAt?: string };
async function* read<T>(name: string): AsyncGenerator<Line<T>> {
const lines = createInterface({ input: createReadStream(`export/${name}.ndjson`), crlfDelay: Infinity });
for await (const line of lines) if (line.trim()) yield JSON.parse(line);
}
async function main() {
let n = 0;
for await (const { id, data } of read<UserDoc>("users")) {
const { email, displayName, plan, createdAt, ...extra } = data;
await pool.query(
`insert into users (firebase_id, email, name, plan, created_at, extra)
values ($1, $2, $3, $4, coalesce($5::timestamptz, now()), $6)
on conflict (firebase_id) do update
set email = excluded.email, name = excluded.name, plan = excluded.plan, extra = excluded.extra`,
[id, email ?? null, displayName ?? null, plan ?? "free", createdAt ?? null, JSON.stringify(extra)],
);
n++;
}
console.log(`users: ${n}`);
n = 0;
for await (const { id, data } of read<PostDoc>("posts")) {
await pool.query(
`insert into posts (firebase_id, user_id, title, body, tags, published_at)
values ($1, (select id from users where firebase_id = $2), $3, $4, $5, $6)
on conflict (firebase_id) do update
set user_id = excluded.user_id, title = excluded.title, body = excluded.body,
tags = excluded.tags, published_at = excluded.published_at`,
[id, data.authorId ?? null, data.title ?? "", data.body ?? "", data.tags ?? [], data.publishedAt ?? null],
);
n++;
}
console.log(`posts: ${n}`);
n = 0;
for await (const { id, parentId, data } of read<CommentDoc>("comments")) {
await pool.query(
`insert into comments (firebase_id, post_id, user_id, text, created_at)
select $1, p.id, (select id from users where firebase_id = $3), $4, coalesce($5::timestamptz, now())
from posts p where p.firebase_id = $2
on conflict (post_id, firebase_id) do update set text = excluded.text`,
[id, parentId, data.authorId ?? null, data.text ?? "", data.createdAt ?? null],
);
n++;
}
console.log(`comments: ${n}`);
// Firebase Auth users, for linking in Step 3.
const { users } = JSON.parse(await readFile("auth-users.json", "utf8")) as {
users: { localId: string; email?: string }[];
};
for (const u of users) {
await pool.query(
"insert into legacy_users (id, email) values ($1, $2) on conflict (id) do update set email = excluded.email",
[u.localId, u.email?.toLowerCase() ?? null],
);
}
console.log(`auth users: ${users.length}`);
await pool.end();
}
main().catch((err) => {
console.error(err);
process.exit(1);
});npx tsx scripts/export-firestore.ts
DATABASE_URL="postgresql://..." npx tsx scripts/load-firestore.tsFirestore data is often messier than you think: missing fields, a number stored as a string, old documents in an older shape. Run the load against a development database first, then check the extra column and any nulls for surprises.
Step 2: Copy your storage files
CloudHike Storage is an S3-compatible bucket, so one script with the AWS SDK can write every file. It reads from Supabase Storage over its S3-compatible endpoint, or from Firebase with the Admin SDK. Files keep their paths, and files already copied with the same size are skipped, so running it again only copies what changed.
# CloudHike Storage (Copy as .env on the Storage card)
S3_ENDPOINT=https://...
S3_REGION=...
S3_BUCKET=...
S3_ACCESS_KEY_ID=...
S3_SECRET_ACCESS_KEY=...
# Supabase: Storage settings, S3 connection. Copy the endpoint and region
# shown there, and create an access key.
SUPABASE_S3_ENDPOINT=https://<project-ref>.supabase.co/storage/v1/s3
SUPABASE_S3_REGION=...
SUPABASE_S3_ACCESS_KEY_ID=...
SUPABASE_S3_SECRET_ACCESS_KEY=...
# Firebase: uses GOOGLE_APPLICATION_CREDENTIALS, as in Step 1b.npm install -D tsx @aws-sdk/client-s3 firebase-adminimport { GetObjectCommand, HeadObjectCommand, ListObjectsV2Command, PutObjectCommand, S3Client } from "@aws-sdk/client-s3";
const target = new S3Client({
endpoint: process.env.S3_ENDPOINT,
region: process.env.S3_REGION,
forcePathStyle: true,
credentials: {
accessKeyId: process.env.S3_ACCESS_KEY_ID!,
secretAccessKey: process.env.S3_SECRET_ACCESS_KEY!,
},
});
const Bucket = process.env.S3_BUCKET!;
let copied = 0;
let skipped = 0;
// Copy one file unless the same key with the same size is already there.
async function copy(key: string, size: number, load: () => Promise<{ body: Uint8Array; type?: string }>) {
const existing = await target.send(new HeadObjectCommand({ Bucket, Key: key })).catch(() => null);
if (existing?.ContentLength === size) {
skipped++;
return;
}
const { body, type } = await load();
await target.send(new PutObjectCommand({ Bucket, Key: key, Body: body, ContentType: type }));
copied++;
if (copied % 100 === 0) console.log(`copied ${copied}...`);
}
async function fromSupabase(sourceBucket: string) {
const source = new S3Client({
endpoint: process.env.SUPABASE_S3_ENDPOINT,
region: process.env.SUPABASE_S3_REGION,
forcePathStyle: true,
credentials: {
accessKeyId: process.env.SUPABASE_S3_ACCESS_KEY_ID!,
secretAccessKey: process.env.SUPABASE_S3_SECRET_ACCESS_KEY!,
},
});
let ContinuationToken: string | undefined;
do {
const page = await source.send(new ListObjectsV2Command({ Bucket: sourceBucket, ContinuationToken }));
for (const obj of page.Contents ?? []) {
if (!obj.Key || obj.Key.endsWith("/")) continue;
await copy(`${sourceBucket}/${obj.Key}`, obj.Size ?? -1, async () => {
const res = await source.send(new GetObjectCommand({ Bucket: sourceBucket, Key: obj.Key }));
return { body: await res.Body!.transformToByteArray(), type: res.ContentType };
});
}
ContinuationToken = page.NextContinuationToken;
} while (ContinuationToken);
}
async function fromFirebase(sourceBucket: string) {
const { applicationDefault, initializeApp } = await import("firebase-admin/app");
const { getStorage } = await import("firebase-admin/storage");
initializeApp({ credential: applicationDefault() });
const [files] = await getStorage().bucket(sourceBucket).getFiles();
for (const file of files) {
if (file.name.endsWith("/")) continue;
await copy(file.name, Number(file.metadata.size ?? -1), async () => {
const [body] = await file.download();
return { body, type: file.metadata.contentType };
});
}
}
async function main() {
const [source, sourceBucket] = process.argv.slice(2);
if (source === "supabase" && sourceBucket) await fromSupabase(sourceBucket);
else if (source === "firebase" && sourceBucket) await fromFirebase(sourceBucket);
else throw new Error("Usage: copy-files.ts supabase <bucket> | firebase <bucket>");
console.log(`done: ${copied} copied, ${skipped} already there`);
}
main().catch((err) => {
console.error(err);
process.exit(1);
});# Supabase: once per bucket. Files land under "<bucket>/<path>".
npx tsx --env-file=.env.migrate scripts/copy-files.ts supabase avatars
# Firebase: your bucket name from the Storage page, such as my-app.firebasestorage.app
npx tsx --env-file=.env.migrate scripts/copy-files.ts firebase my-app.firebasestorage.appThe script holds one file in memory at a time, which is fine for images and documents. For files of several GB, switch PutObjectCommand to the multipart Upload helper from @aws-sdk/lib-storage.
Fix the URLs stored in your database
CloudHike buckets are private. Instead of storing public URLs, store the object key and create a short-lived presigned URL when you show the file. If your tables hold Supabase public URLs, turn them into keys:
-- https://<ref>.supabase.co/storage/v1/object/public/avatars/u1.png -> avatars/u1.png
update profiles
set avatar_url = regexp_replace(avatar_url, '^https://[^/]+/storage/v1/object/public/', '')
where avatar_url like 'https://%/storage/v1/object/public/%';Browser uploads also need your site listed under Storage → Settings → Allowed upload domains. Development environments already allow localhost.
Step 3: Move users without forcing a password reset
This is the part to plan most carefully. Passwords are stored as one-way hashes, and the CloudHike Auth docs do not describe a way to import users or password hashes, or an admin endpoint that creates users. So users can't be copied in bulk. What you can do, using only documented endpoints, is move each user the next time they sign in.
- Email and password users: keep the old auth running for a few weeks. When someone signs in, try CloudHike first. If that fails, check the password with the old provider. If it's right, create their CloudHike account with the same email and password, then sign them in. They never notice.
- Google and GitHub users: set up GitHub and Google sign-in on the Auth card. They sign in with the same provider, and you link the new account to their old data by email.
- Users who don't come back during the window: after you turn the old auth off, they sign up again with the same email, and you link them by email. From then on, the normal password reset flow works for them.
Turn on Require a verified email before sign-in on the Auth page's Providers tab. Moved users then confirm their address once, and linking by email is safe because every email has been proven.
import "server-only";
// Checks a password against the old provider. Remove this file after the window.
export async function checkLegacyPassword(email: string, password: string) {
if (process.env.SUPABASE_URL) {
const res = await fetch(`${process.env.SUPABASE_URL}/auth/v1/token?grant_type=password`, {
method: "POST",
headers: { "content-type": "application/json", apikey: process.env.SUPABASE_ANON_KEY! },
body: JSON.stringify({ email, password }),
});
if (!res.ok) return null;
const { user } = await res.json();
return { id: String(user.id) };
}
if (process.env.FIREBASE_WEB_API_KEY) {
const res = await fetch(
`https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=${process.env.FIREBASE_WEB_API_KEY}`,
{
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ email, password, returnSecureToken: true }),
},
);
if (!res.ok) return null;
const data = await res.json();
return { id: String(data.localId) };
}
return null;
}"use server";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import { pool } from "@/lib/db";
import { checkLegacyPassword } from "@/lib/legacy-auth";
export type LoginState = { error: string } | null;
function auth(path: string, body: object) {
return fetch(`${process.env.AUTH_URL}${path}`, {
method: "POST",
headers: { "content-type": "application/json", "x-api-key": process.env.AUTH_PUBLISHABLE_KEY! },
body: JSON.stringify(body),
});
}
export async function signIn(_prev: LoginState, form: FormData): Promise<LoginState> {
const email = String(form.get("email") ?? "").trim().toLowerCase();
const password = String(form.get("password") ?? "");
if (!email || !password) return { error: "Please enter your email and password." };
let res = await auth("/sign-in/email", { email, password });
// 403 means the account exists but the email isn't verified yet.
if (!res.ok && res.status !== 403) {
const legacy = await checkLegacyPassword(email, password);
if (!legacy) return { error: "Wrong email or password." };
// New passwords need at least 8 characters; older ones may be shorter.
if (password.length < 8) {
return { error: "Please create your account again with a password of at least 8 characters." };
}
const created = await auth("/sign-up/email", { name: email.split("@")[0], email, password });
if (!created.ok) {
console.error("Moving user failed", created.status, await created.text());
return { error: "We couldn't move your account. Please try again." };
}
const { user } = await created.json();
await pool.query(
"update legacy_users set cloudhike_user_id = $1 where id::text = $2 and cloudhike_user_id is null",
[user.id, legacy.id],
);
res = await auth("/sign-in/email", { email, password });
}
if (res.status === 403) return { error: "Please confirm your email first. We've sent you a link." };
if (!res.ok) return { error: "Wrong email or password." };
const { token } = await res.json();
(await cookies()).set("session", token, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
path: "/",
});
redirect("/dashboard");
}Your old rows still point at old user ids, and new CloudHike users get new ids. legacy_users is the bridge: it maps each CloudHike user to the app user id your tables use. The helper below reads the session from the cookie, links Google, GitHub and returning users by their verified email the first time it sees them, and gives brand-new users a fresh app id, so your tables keep one kind of user id.
import "server-only";
import { cookies } from "next/headers";
import { cache } from "react";
import { pool } from "@/lib/db";
export const currentUser = cache(async () => {
const token = (await cookies()).get("session")?.value;
if (!token) return null;
const res = await fetch(`${process.env.AUTH_URL}/get-session`, {
headers: { "x-api-key": process.env.AUTH_PUBLISHABLE_KEY!, authorization: `Bearer ${token}` },
});
const session = res.ok ? await res.json() : null;
if (!session?.user) return null;
const { id, email } = session.user as { id: string; email: string };
// 1. Already linked?
const linked = await pool.query<{ id: string }>(
"select id::text from legacy_users where cloudhike_user_id = $1",
[id],
);
if (linked.rows[0]) return { id, email, appUserId: linked.rows[0].id };
// 2. An old user with the same email. Safe only because "Require a verified
// email" is on, and Google and GitHub emails are verified.
const byEmail = await pool.query<{ id: string }>(
`update legacy_users set cloudhike_user_id = $1
where id = (select id from legacy_users
where cloudhike_user_id is null and lower(email) = lower($2) limit 1)
returning id::text`,
[id, email],
);
if (byEmail.rows[0]) return { id, email, appUserId: byEmail.rows[0].id };
// 3. A brand-new user: give them an app id of the same kind as the old ones.
const created = await pool.query<{ id: string }>(
`insert into legacy_users (id, email, cloudhike_user_id) values (gen_random_uuid(), $2, $1)
on conflict (cloudhike_user_id) do update set email = excluded.email
returning id::text`,
[id, email],
);
return { id, email, appUserId: created.rows[0].id };
});Need the full sign-up, sign-in and cookie setup? The Next.js authentication guide builds it step by step.
Step 4: Replace client SDK calls with server code
Supabase and Firebase let the browser query the database directly, with row-level security or security rules deciding what each user may see. CloudHike's DATABASE_URL is a server-side secret, so data access moves into Server Components and Server Actions. In return, your rules become ordinary code you can test.
Reading data
"use client";
// const { data } = await supabase.from("posts").select("*").eq("user_id", user.id);
// (Firebase: getDocs(query(collection(db, "posts"), where("authorId", "==", uid))))import { redirect } from "next/navigation";
import { pool } from "@/lib/db";
import { currentUser } from "@/lib/session";
export default async function Dashboard() {
const user = await currentUser();
if (!user) redirect("/login");
// This WHERE clause is your old row-level security policy.
// With the Firestore schema from Step 1b, use
// "where user_id = (select id from users where firebase_id = $1)".
const { rows: posts } = await pool.query<{ id: number; title: string }>(
"select id, title from posts where user_id = $1 order by id desc limit 50",
[user.appUserId],
);
return (
<ul>
{posts.map((p) => (
<li key={p.id}>{p.title}</li>
))}
</ul>
);
}Writing data
"use server";
import { revalidatePath } from "next/cache";
import { pool } from "@/lib/db";
import { currentUser } from "@/lib/session";
// Was: supabase.from("posts").insert(...) or addDoc(collection(db, "posts"), ...)
export async function createPost(form: FormData) {
const user = await currentUser();
if (!user) throw new Error("Not signed in");
const title = String(form.get("title") ?? "").trim();
if (!title || title.length > 200) throw new Error("Title must be 1 to 200 characters");
await pool.query("insert into posts (user_id, title) values ($1, $2)", [user.appUserId, title]);
revalidatePath("/dashboard");
}import "server-only";
import { Pool } from "pg";
const globalForDb = globalThis as unknown as { pool?: Pool };
export const pool = globalForDb.pool ?? new Pool({ connectionString: process.env.DATABASE_URL, max: 5 });
if (process.env.NODE_ENV !== "production") globalForDb.pool = pool;These queries assume a Supabase-style schema where posts.user_id holds the old user id. With the Firestore schema, look the user up by firebase_id as the comment shows, and create a users row for brand-new users when they first sign in. If you'd rather have typed queries, the Drizzle guide shows how to generate a schema from your imported tables.
- Realtime listeners (
onSnapshot, Supabase Realtime): the CloudHike docs don't list a realtime service. For dashboards, callrouter.refresh()on an interval or after an action. If live updates are core to your app, keep that piece on its current service for now. - Edge and Cloud Functions: most become route handlers in your Next.js app. Slow ones become background jobs.
- Protecting pages: check
currentUser()in each page and action, and see protecting routes with proxy for a first line of defense.
Cutover checklist
- Rehearse. Run every step above into a development environment and use the new app there for a few days.
- Set up Auth. Add your sites under Sites users can return to, set up Google and GitHub with your own OAuth apps if you use them, and adjust the verification and reset emails.
- Deploy the new app to a preview URL with the CloudHike variables. Test sign-in for a moved user, a Google user and a brand-new user, plus uploads and your key pages.
- Freeze writes. Announce a short window and put the old app in read-only mode.
- Copy for real. From Supabase: re-create
legacy_usersin the Supabase SQL editor, re-run Import database (it replaces the rehearsal data), then re-run thealter tablestatements from Step 1a. From Firebase: re-run the export and load. Then re-run the file copy; it only copies what changed. - Check the counts. Compare row counts and file counts with the source.
- Switch production. Set the production environment variables, add your domain under Allowed upload domains, and deploy.
- Keep the old project running for the transition window, with its auth still answering password checks. Watch your logs for failed moves.
- Clean up. After the window, delete
lib/legacy-auth.ts, the Supabase or Firebase keys,auth-users.jsonand the service account key, then shut down the old project.
Plan limits for database size, storage and active users are on the pricing page. If you are moving a large app, check them before cutover day.
Frequently asked questions
Can I migrate from Supabase without losing data?
Yes for your database: it is plain Postgres, so tables, data, views, functions and indexes copy across with an import or pg_dump. Auth users, storage files, edge functions and row-level security policies need their own steps, so check each one before you switch over.
How do I migrate Firestore to Postgres?
Export each collection to JSON with the Firebase Admin SDK, design a table for each collection (subcollections become child tables with foreign keys), then load the JSON with a script that upserts on the old document id. Run it against a test database first.
Will my users have to reset their passwords?
Not if you keep the old auth running for a while. When a user signs in, check their password with the old provider and create their new account with the same password. Only users who don't sign in during that window need to sign up again with the same email.
Can I export password hashes from Firebase or Supabase?
Firebase's auth:export command and a Supabase database dump both include password hashes. The new system has to support importing those exact hash formats for them to be useful. The CloudHike Auth docs don't describe a hash import, so this guide moves users at sign-in instead.
How long does a migration from Firebase or Supabase take?
A small Supabase app can move in a day, since the database copies as is. A Firebase app takes longer because Firestore data has to be remodeled into tables. Plan a few weeks of overlap for user sign-ins either way.
