SkybuDocs

Ferdigheter · Oppskrifter

Leave Supabase

Move an app's Supabase database, users and files to Skybu with skybu supabase import, and rewrite the app so it no longer needs supabase-js.

skill://playbooks/leave-supabaseAgenter leser den med resources/read eller skills_read. Den er skrevet på engelsk, for agentene.

skybu supabase import copies a Supabase project's database to Skybu: tables, rows, functions, triggers, row-level security policies, grants, and the users with their password hashes. With --storage it copies the files too. What does not move are the services supabase-js talks to: Supabase Auth, the REST API (PostgREST), Storage and Realtime. So the work has two halves: the import, which is one command, and the app, where every data call moves to the server and sign-in moves to Better Auth inside the app.

In short

  1. Check that you have a shell with skybu and the Postgres client tools; if you only have MCP, the user runs the import commands.
  2. skybu supabase check, and fix the blockers.
  3. Import into a test project, and build against that copy.
  4. Create Better Auth's tables and copy the users into them, as app_owner.
  5. Replace supabase-js: Better Auth for sign-in, server routes that run queries as the signed-in user.
  6. Move files, Realtime, webhooks, cron jobs and Edge Functions.
  7. Cut over: stop writes on Supabase, import into the real project, run the SQL again, deploy, point DNS.

Step 1: what you need

  • A shell with the Skybu CLI (skybu, Node 24 or newer), logged in with a CLI token from the dashboard.
  • psql, pg_dump and pg_restore, version 17 or newer and at least the Supabase server's version. The CLI finds them on PATH, in Homebrew's libpq, in /usr/lib/postgresql/*/bin, or in SKYBU_PG_BIN.
  • SUPABASE_DB_URL: the session pooler or direct connection string from Supabase (port 5432). The transaction pooler (port 6543) is refused, because it cannot hold the snapshot the copy uses.
  • For files: SUPABASE_URL (https://<ref>.supabase.co) and SUPABASE_SERVICE_ROLE_KEY.

Have the user set the secrets in the shell's environment. Do not ask for them in chat or write them to files.

With only MCP, you cannot run the import or the SQL below: they need the Postgres tools and a database tunnel, which needs a CLI token. Create the project with create_project, give the user the commands from Steps 2, 3, 4 and 7 to run, and do the code in Steps 5 and 6 yourself. Do not call create_database first: the import creates the database itself, named main, and fails if that name is taken.

Step 2: check

SUPABASE_DB_URL='postgres://…:5432/postgres' skybu supabase check

It reads the source in one read-only snapshot and prints a verdict, a rough downtime for the copy, and findings:

LevelExamplesWhat to do
BLOCKER (exit code 2)Extensions Skybu does not have; foreign keys or column types pointing into Supabase's own schemas; policies for Supabase's internal rolesFix in Supabase first. --ignore-extension <name> leaves out an extension nothing uses.
CHANGESign-in, database webhooks, Realtime, pg_cron jobs, vault secrets, large objects, storage, functions using Supabase-only objectsWork for Steps 5 and 6.
OKExtensions created on Skybu, row-level security copiedNothing.

--json gives the same as data.

Step 3: a test import

Import into a project you can throw away, so the real one stays clean until the cut-over:

{ "name": "create_project", "arguments": { "name": "kundeportal-test" } }
SUPABASE_DB_URL='…' skybu supabase import --project kundeportal-test

What it does:

  • Takes one snapshot of the source; writes made after it starts are not copied.
  • Creates a database (main, or --name) in Supabase mode: roles anon, authenticated and service_role, with the app's role app_rw a member of all three and allowed past row-level security, as the service role key was. It refuses if the data needs more than the database's storage.
  • Copies every schema that is not Supabase's own, plus auth.users, auth.identities and the other auth tables your schema refers to, and the triggers on them whose functions are yours. Database webhooks are skipped.
  • Creates auth.uid(), auth.jwt(), auth.role() and auth.email(), which read request.jwt.claims, so the policies work unchanged.
  • Copies the grants of anon, authenticated and service_role as in the source, and grants app_rw and app_ro.
  • Compares row counts table by table. Success ends with All N tables match; restore errors, differing counts and failed files are listed and the exit code is 1.
  • With --storage, copies each file to the project's bucket as <bucket>/<path>, if it fits the file quota.

Step 4: users into Better Auth

Run this SQL once as app_owner, through skybu db connect <project>/main --role owner and psql with the printed URL. It puts Better Auth's tables in their own schema, so anon and authenticated get no rights on sessions or password hashes:

create schema better_auth;
create table better_auth."user" ("id" uuid default gen_random_uuid() not null primary key, "name" text not null, "email" text not null unique, "emailVerified" boolean not null, "image" text, "createdAt" timestamptz default current_timestamp not null, "updatedAt" timestamptz default current_timestamp not null);
create table better_auth."session" ("id" uuid default gen_random_uuid() not null primary key, "expiresAt" timestamptz not null, "token" text not null unique, "createdAt" timestamptz default current_timestamp not null, "updatedAt" timestamptz not null, "ipAddress" text, "userAgent" text, "userId" uuid not null references better_auth."user" ("id") on delete cascade);
create table better_auth."account" ("id" uuid default gen_random_uuid() not null primary key, "accountId" text not null, "providerId" text not null, "userId" uuid not null references better_auth."user" ("id") on delete cascade, "accessToken" text, "refreshToken" text, "idToken" text, "accessTokenExpiresAt" timestamptz, "refreshTokenExpiresAt" timestamptz, "scope" text, "password" text, "createdAt" timestamptz default current_timestamp not null, "updatedAt" timestamptz not null);
create table better_auth."verification" ("id" uuid default gen_random_uuid() not null primary key, "identifier" text not null, "value" text not null, "expiresAt" timestamptz not null, "createdAt" timestamptz default current_timestamp not null, "updatedAt" timestamptz default current_timestamp not null);
create index "session_userId_idx" on better_auth."session" ("userId");
create index "account_userId_idx" on better_auth."account" ("userId");
create index "verification_identifier_idx" on better_auth."verification" ("identifier");
grant usage on schema better_auth to app_rw;
grant select, insert, update, delete on all tables in schema better_auth to app_rw;

Then copy the users, keeping each id, so every foreign key to auth.users and every policy comparing auth.uid() still matches. Running it again adds nothing:

begin;
insert into better_auth."user" ("id", "name", "email", "emailVerified", "image", "createdAt", "updatedAt")
select u.id,
  coalesce(nullif(u.raw_user_meta_data ->> 'name', ''), nullif(u.raw_user_meta_data ->> 'full_name', ''), split_part(u.email, '@', 1)),
  lower(u.email), u.email_confirmed_at is not null,
  coalesce(u.raw_user_meta_data ->> 'avatar_url', u.raw_user_meta_data ->> 'picture'),
  coalesce(u.created_at, now()), coalesce(u.updated_at, u.created_at, now())
from auth.users u
where u.email is not null and u.deleted_at is null and not coalesce(u.is_anonymous, false)
on conflict do nothing;
insert into better_auth."account" ("accountId", "providerId", "userId", "password", "createdAt", "updatedAt")
select u.id::text, 'credential', u.id, u.encrypted_password, coalesce(u.created_at, now()), now()
from auth.users u join better_auth."user" b on b.id = u.id
where u.encrypted_password like '$2%'
  and not exists (select 1 from better_auth."account" a where a."userId" = u.id and a."providerId" = 'credential');
insert into better_auth."account" ("accountId", "providerId", "userId", "createdAt", "updatedAt")
select i.provider_id, case i.provider when 'azure' then 'microsoft' else i.provider end, i.user_id, coalesce(i.created_at, now()), now()
from auth.identities i join better_auth."user" b on b.id = i.user_id
where i.provider not in ('email', 'phone')
  and not exists (select 1 from better_auth."account" a
    where a."providerId" = case i.provider when 'azure' then 'microsoft' else i.provider end and a."accountId" = i.provider_id);
commit;

Deleted, anonymous and email-less users are left out. Sessions, refresh tokens and MFA factors do not move: everyone signs in once more, and users who had MFA enrol again.

Step 5: the app

Sign-in

Supabase stored bcrypt hashes; Better Auth uses scrypt. This setup accepts both, so nobody has to reset a password, and keeps auth.users up to date so your foreign keys and triggers such as on_auth_user_created keep working:

import bcrypt from "bcryptjs";
import { betterAuth } from "better-auth";
import { hashPassword, verifyPassword } from "better-auth/crypto";
import pg from "pg";

export const app = new pg.Pool({ connectionString: process.env.DATABASE_URL, max: 8 });
const database = new pg.Pool({ connectionString: process.env.DATABASE_URL, options: "-c search_path=better_auth", max: 4 });

export const auth = betterAuth({
  database,
  emailAndPassword: {
    enabled: true,
    password: {
      hash: hashPassword,
      verify: ({ hash, password }) => (hash.startsWith("$2") ? bcrypt.compare(password, hash) : verifyPassword({ hash, password })),
    },
  },
  advanced: { database: { generateId: "uuid" } },
  databaseHooks: {
    user: {
      create: {
        after: async (user) => {
          try {
            await app.query(
              `insert into auth.users (instance_id, id, aud, role, email, raw_user_meta_data, email_confirmed_at, created_at, updated_at)
               values ('00000000-0000-0000-0000-000000000000', $1, 'authenticated', 'authenticated', $2, jsonb_build_object('name', $3::text), case when $4 then now() end, now(), now())`,
              [user.id, user.email, user.name, user.emailVerified],
            );
          } catch (error) {
            await database.query(`delete from "user" where id = $1`, [user.id]);
            throw error;
          }
        },
      },
      update: { after: async (user) => void (await app.query("update auth.users set email = $2, updated_at = now() where id = $1 and email is distinct from $2", [user.id, user.email])) },
      delete: { after: async (user) => void (await app.query("delete from auth.users where id = $1", [user.id])) },
    },
  },
});

Use better-auth@1.7.14, bcryptjs@3.0.3 and pg@8.16.3, the versions Skybu tests this with. Set BETTER_AUTH_SECRET, the app's addresses and the routes as in skill://playbooks/add-login, which also covers password-reset email.

supabase-jsBetter Auth
auth.signUp, auth.signInWithPasswordauthClient.signUp.email, authClient.signIn.email
auth.signInWithOAuth({ provider })authClient.signIn.social({ provider }); register /api/auth/callback/<provider>
auth.signOut()authClient.signOut()
auth.getUser() on the serverauth.api.getSession({ headers })
auth.onAuthStateChangeauthClient.useSession()

Data

supabase.from() and .rpc() in the browser become routes on your server. The server checks the session, then runs the query as that user in a transaction, the way PostgREST did, so the same policies apply:

async function asUser<T>(userId: string, work: (db: pg.PoolClient) => Promise<T>): Promise<T> {
  const client = await app.connect();
  try {
    await client.query("begin");
    await client.query("select set_config('role', 'authenticated', true), set_config('request.jwt.claims', $1, true)",
      [JSON.stringify({ sub: userId, role: "authenticated", aal: "aal1" })]);
    const result = await work(client);
    await client.query("commit");
    return result;
  } catch (error) {
    await client.query("rollback");
    throw error;
  } finally {
    client.release();
  }
}
  • It has to be a transaction: set_config(…, true) ends with it, so one user's role never leaks to the next request.
  • For signed-out visitors, do the same with role anon.
  • Policies that read auth.jwt() ->> 'email' or app_metadata need those in the claims too; Supabase kept app_metadata in auth.users.raw_app_meta_data.
  • Plain queries on app bypass row-level security, as the service role key did. Keep them out of code that acts for a user.
  • .rpc('fn', { a: 1 }) becomes select * from public.fn(a => $1).
  • pg throws where supabase-js returned { error }; a refused write is code 42501 (answer 403).
  • There is no 1,000-row cap any more: add limit. bigint and numeric arrive as strings.

drizzle-kit pull against the imported database writes a Drizzle schema to replace supabase gen types. Through the tunnel, node-postgres needs uselibpqcompat=true&sslmode=require in place of sslmode=require, because your machine does not have the database's CA.

Step 6: the rest

SupabaseOn Skybu
StorageThe project's bucket, through SKYBU_S3_*; files are at <bucket>/<path>. Buckets are private, so public URLs become presigned URLs, and access is checked in your route (skill://files/store-files).
RealtimeA trigger calls pg_notify; one server connection runs LISTEN and forwards ids to browsers. Notifications skip row-level security.
Database webhooksSend the request from the code that makes the change.
pg_cronA timer in the app.
VaultThe app's variables, sensitive: true (skill://apps/environment-variables).
Edge FunctionsRoutes in the app; Deno.env.get becomes process.env.

Deploy the app to the test project with deploy_files (skill://apps/deploy-an-app) and ask the user for its data class; an app with user accounts is at least personal. Sign in with a few real accounts, including one per OAuth provider, before the cut-over.

Step 7: cut over

  1. Stop writes on Supabase.
  2. skybu supabase import --project <real project> --storage.
  3. Run the two SQL blocks from Step 4 against the new database.
  4. Set the variables and deploy the app to the real project.
  5. Point the domain at Skybu (skill://domains/custom-domain).

The user deletes the test project in the dashboard when it is no longer needed; agents cannot delete.

Things to know

  • A project whose database is in Supabase mode gets no preview databases: pull request previews run without DATABASE_URL.
  • Import into a project without a database. Apps get the project's database named main, else the oldest, so an import under another --name next to an existing main would not reach the app.
  • create_database with the supabase argument only creates the empty, Supabase-shaped database; the CLI does that itself during the import.
  • Schema changes after the import are migrations as app_owner, with a restore point first (skill://playbooks/app-with-a-database).