Bring an existing application #
On this page
Prompt:
Move this app here from where it runs now.
Also works:
- "Host my existing backend on Turn Zero Cloud."
If the app serves only static files, follow Publish a static site. A static site has no server charge.
An unchanged Python server has no deploy path on Turn Zero Cloud, but you can still move its static frontend and import its PostgreSQL data.
Use a server to move an existing Express, Next.js, or other Node.js server with its current code. For the Next.js build and development checks, follow Deploy an existing Next.js server. If you want to rewrite the backend, first check whether its handlers fit the function limits. A rewrite runs in a separate serverless application. Move an Express notes app to functions shows how to keep the frontend while rewriting the handlers. This takes more code changes than keeping an existing Express server. Functions have no awake-time server charge, and their usage is charged by the number of calls.
Use the server route below to keep an existing Express or other Node.js server. A server is charged for the time it is awake. Compare both options using the pricing calculator. Include database and storage costs wherever you need those services.
For the move, include server awake time in development and production, any function calls and other metered backend actions, and data transfer. Include database hosting, database and file storage, and any custom domain you attach. If you use app email or jobs, include email recipients and job run time. Include the old host’s charges while both copies are running and any separate mail provider or domain registration costs.
For Cloud rates and units, read the pricing page or call read_rate_card. Ask the other providers for their rates. Use read_balance to see how much of your Free Allowance remains.
Keep the site and backend in one server application if they need to share a hostname for cookies, sign-in callbacks or relative API URLs. Use a separate static site if the backend can have its own hostname. Check which URLs the site calls, which requests it can make across hostnames, and how users sign in.
A deployed app can open a direct PostgreSQL connection only to its Turn Zero Cloud database. If your database is hosted elsewhere, move the data here or use the provider's HTTPS interface if it offers one. To move the database, follow Carry existing records into the database.
Check what to bring from your old host before you start. Use the checklist for Netlify, Vercel, or Replit.
Four steps move it. None of them writes a new project's files over your code.
- Check that the code fits how the platform runs it (step 1: Check the code against the runtime).
- Move the keys off the old host (step 2: Move the keys off the old host).
- Carry any records kept in files into the database as one migration file (step 3: Carry existing records into the database).
- Create the application, submit its manifest, and deploy it (step 4: Create, declare, and deploy).
To try the migrated app with a database you can discard, follow Run against your own PostgreSQL and choose the in-memory PGlite or Docker setup. If the app needs Cloud services or shared development data, follow the local run that connects to Cloud.
What your AI does #
Reads the
move-existing-appskill (read_context, idskill:move-existing-app) and follows it.Checks the code against what the platform needs to run it, as step 1 (Check the code against the runtime) describes, and changes only what does not fit.
Leaves your code in place. The
turnzerocommand'sscaffoldstarts a new application, so your AI coding agent does not run it here.For a server, uses the size you already named, or asks which size it starts on. For a site of static files alone, follows Publish a static site, with no size to choose. It also asks where each key the old host held is kept.
Uses the audience stated in your project, including its README: a team, company or invited people mean
invited; visitors, customers or anyone meanpublic. Otherwise asks once whether anyone may use it or only people you invite; if you do not answer, choosespublic. With nobody to ask, chooses and reportspublic, exceptinvitedfor a server without its own sign-in.For that server, explains that the code checks no caller and how to open access. For a static site, chooses
publicand reports that anyone can reach it. To restrict it, sets the manifest'saudiencetoinvited, callssubmit_manifest, and deploys as required (step 4: Create, declare, and deploy).Where the old copy kept records in a file, writes the migration file that carries them into the database, as step 3 (Carry existing records into the database) describes.
For a server with no size named and nobody to ask, uses Shared 0.5 GB with its default sleep setting. It reports why it chose that size, that awake time draws the account's Free Allowance, and that you may request Shared 1 GB for more memory or CPU.
A shared database is one monthly item for the application. Each daily billing run charges one day’s share for the items it finds held. Stored files are charged by size (Stay inside the Free Allowance).
What you need #
Node.js 24 or later, and npm, installed on your computer. See What your computer needs.
For a server, select the size it starts on: Shared 0.5 GB or Shared 1 GB. For static files alone, follow Publish a static site, with no size to choose.
If you want the lower-cost choice, pick Shared 0.5 GB and keep its default sleep setting. A server is charged for the time it is awake. Shared 0.5 GB has the lower rate, and by default it sleeps when it is idle. For actual amounts, your AI assistant reads the rates with
read_rate_card, and this month's cost and remaining balance withread_balance. The pricing page lists the rates.The keys the application uses at its old host.
Before your AI starts #
For the AI assistant: Check the following before starting.
- Your AI assistant connected and signed in (Connect your AI assistant).
- The settings the code reads from
process.env, its environment variables, and the outside APIs it calls with a key. - Your application's own folders, kept as they are. The
app/andsystem/layout is the onescaffoldwrites for a new project, andscaffoldrefuses a folder that already holds an application. A library package your code uses goes in at the folder that holds your code'spackage.json, as the section 5. Install a package's compiled code of Use the feature package library describes.
Steps #
An existing application follows the steps of Deploy from your computer. The steps below say what differs for code that already runs elsewhere.
An Express app that keeps its data in a local JSON file usually needs these six changes:
- A database for the data. The running copy's disk is not kept, so the records move to a database (step 1: Check the code against the runtime).
- A one-time import. The records already in the file move as one migration file (step 3: Carry existing records into the database).
- The port. The server listens on the port in
PORT(step 1: Check the code against the runtime). - A health route. The manifest names a path, usually
/health, that returns 200 once the app is ready (step 1: Check the code against the runtime). - The web client's build folder. The built front-end files go under
client/besidepackage.json, where the platform serves them (Serve a web client). - Who may reach the app. Choose the manifest's required
audience, which has no default, before writing the manifest. Forinvited, declare the accounts service for sign-in through the application's end-user realm (step 4: Create, declare, and deploy).
1. Check the code against the runtime #
Before changing the code or building the app, check the deploy ZIP limits. Check the upload size, the expanded size and the number and size of served files.
A server application runs on the platform as one Node.js server. It listens on the port in the PORT environment variable (Node.js Runtime). Its manifest names a health path: a route that responds with status 200 once the server is ready (The deploy health check). An application with a fixed port, or no health path, needs those two changes.
A running copy's own disk is not kept. A new copy starts with only what its deploy built, at each deploy, promote, rollback, and restart_application, after an idle stop, and whenever the platform replaces a copy. Whatever the code wrote to the file system, /tmp included, is lost.
Code that keeps uploads, a SQLite file, or other state on disk moves it before the first deploy: files to a storage area, and records to a database (Add a database). A file the code writes and reads back within one request can stay on the disk. Step 3 (Carry existing records into the database) carries the records already kept in a file.
The folder your AI coding agent deploys holds package.json at its top. If the app sits inside a larger project, use The two project layouts to pick that folder. If you make the ZIP yourself, ZIP the contents of that folder so package.json is at the ZIP's root. The deploy leaves out node_modules, .git, the AI coding agents' own files such as .claude and .mcp.json, and the .env and .env.* files anywhere in the folder. It also leaves out paths listed in the folder's top-level .deployignore (What the deploy zip holds).
The command never applies .gitignore; it prints a note: when the zip includes a file the top-level .gitignore lists. To exclude a file, list it in the top-level .deployignore, which uses .gitignore syntax.
Before the first deploy, your AI coding agent runs the command's hash --list, which lists every file the zip would hold without uploading anything. It moves outside the folder any other file that holds the old host's values, such as .envrc or .dev.vars.
The platform runs no build script of yours. Run your project's build before you deploy, and include the output that its start script needs in the folder you send. The image build installs runtime dependencies without your root install scripts or development dependencies; dependencies' own install scripts may run. The running copy then runs npm start. What the image build installs gives the details.
2. Move the keys off the old host #
Your AI coding agent moves each value the old host's environment held. To store each secret on the platform, it calls store_secret and runs the command line that call returns (Store a secret). A value from .env goes alone into a temporary file outside the application's folder, never as the whole KEY=value line (Supply the value without exposing it). Where a value goes depends on what it is and how the code uses it:
- For a key sent to an outside API, use a declared upstream when the code can call that API through the platform's gateway, which adds the key. An SDK that reads its base URL and key from settings can use that route without code changes (An unchanged SDK). If the code must call a fixed provider address and you cannot change it, bind the stored key in the manifest's
settingsto the variable it reads, and list the provider's host inegress. - A secret the code uses itself, such as a webhook signing secret, is stored and bound to a setting in the manifest's
settings(Bind a value to a setting). - For a value such as
SITE_TITLEthat can appear in the manifest, use{"value": "<text>"}insettings. The manifest supplies the same value in every environment (Set a value that is not secret). A value that differs between development and production is stored and bound like a secret instead. If your AI coding agent may not read the value, give it the non-secret value in chat, or store and bind it like a secret (Supply the value without exposing it).
When moving to the Cloud database, check both the web server and each scheduled script for DATABASE_URL. Change those reads to APP_DATABASE_URL and verify both paths use the restored database in development. Add a database explains the connection settings.
Store each secret before the first deploy. With development on, store each bound secret under the same name at each environment's scope before deploying or promoting to that environment. Ask the person whether production needs a different value. A deploy or promote refuses setting_secret_missing if a bound name has no value at its target environment's scope.
List what the app sends and which sender address it needs. Turn Zero application email fits occasional notices and sends from no-reply@mail.ai.host. Keep your mail provider if you need your own sender address, attachments, newsletters or more sends than Turn Zero allows.
3. Carry existing records into the database #
Skip this step if you have no records to import.
Restore a PostgreSQL dump. Create the app and submit its manifest with the database declared. This creates the development database. Choose the restore form before startup migrations create tables. Use pg_restore for a custom archive or psql for a plain SQL dump, with the development database credential. Rehearse the schema and data load in development.
For production, deploy before connecting to its separate database. Serverless .sql migrations are versioned and have an 8 MiB total limit and a five-minute run limit.
Import records from a file. Records such as those in data/notes.json move into the database as one migration file: a numbered .sql file in the migrations/ folder. The application's start code applies that file once in each database, in its own transaction, as it applies the schema's migrations (Keep the schema as migrations).
Before importing, check that the application's startup runs migrations. For an ESM server with no migration runner, use the Database package's applyMigrations at startup. If your AI assistant cannot reach the library, use the runner on pg alone. For a CommonJS application using Express, use CommonJS and Express for the server and CommonJS migration helper for the runner.
For one complete CommonJS file using the text-ID records below, use A complete CommonJS server.
The runner imports the records into development when the application first starts with that file, on your machine or deployed. It imports them into production when the first deploy or promote that includes the file starts the application there. The platform does not perform the import itself. This sample carries records through the application's own migrations.
The sample below writes migrations/0002_import_notes.sql from data/notes.json, whose records each hold a title. It fills the notes table that Add a database creates. The script accepts a JSON array or an object of records, including a file that starts with a byte-order mark. It writes the records as one JSON string, with $rows$ at each end to mark the string for PostgreSQL. That keeps quotes in the records from needing escapes. PostgreSQL's jsonb_to_recordset then turns each record into a row. A test runs this sample over the Database package's test double and checks the imported rows.
If your records have other fields, such as text and created, make the notes table match them through a schema migration, then pass their names and PostgreSQL types to the script. To preserve text IDs, use Keep original text IDs below. Records with other fields shows records holding id, text and created.
// scripts/write_import_migration.mjs: writes the next numbered migration that carries a JSON file's records into one table.
import { readdirSync, readFileSync, writeFileSync } from 'node:fs';
// The records file, the table, and its columns with their types; with none given, data/notes.json into notes.
const [file = 'data/notes.json', table = 'notes', columns = 'title text'] = process.argv.slice(2);
// The records as one JSON array, whether the file holds an array or an object of records.
const records = JSON.parse(readFileSync(file, 'utf8').trimStart());
const list = Array.isArray(records) ? records : Object.values(records);
if (list.length === 0) throw new Error(`${file} holds no records.`);
const rows = JSON.stringify(list);
if (rows.includes('$rows$')) throw new Error('A record holds the text $rows$: choose another quote tag.');
// One import for each table, numbered after the highest migration.
const existing = readdirSync('migrations');
if (existing.some((name) => name.endsWith(`_import_${table}.sql`))) throw new Error(`migrations/ already holds an import of ${table}.`);
const next = Math.max(0, ...existing.map((name) => Number.parseInt(name, 10)).filter(Number.isFinite)) + 1;
const target = `migrations/${String(next).padStart(4, '0')}_import_${table}.sql`;
// The column names, without their types, for the INSERT and SELECT lists.
const names = columns.split(',').map((column) => column.trim().split(/\s+/)[0]).join(', ');
writeFileSync(target, [
`INSERT INTO "${table}" (${names})`,
`SELECT ${names}`,
`FROM jsonb_to_recordset($rows$${rows}$rows$::jsonb) AS r(${columns});`,
'',
].join('\n'));
console.log(`wrote ${target}: ${list.length} records into ${table}`);
Run the script once on your machine from the project's root with node scripts/write_import_migration.mjs. With no arguments, it reads data/notes.json and imports title text into notes. To use another file, table or set of columns, pass node scripts/write_import_migration.mjs <records file> <table> "<column> <type>, ..."; each argument replaces its default in order. In the third argument, give each column's key in the records followed by its PostgreSQL type, separating columns with commas. The script derives the INSERT and SELECT column names from that list.
The script numbers the file after the highest migration in migrations/ and names it NNNN_import_<table>.sql. With 0001_notes.sql as the highest migration, the default run writes migrations/0002_import_notes.sql. Keep the file it writes with the other migrations. On success, it prints wrote <file>: <n> records into <table>.
The script writes nothing if the file holds no records, a record holds $rows$, or migrations/ already holds an import for the table. Check an empty source file before retrying. If a record holds $rows$, choose another quote tag in the script before running it again. If an import already exists, check that migration before proceeding; do not overwrite it.
For records in a CSV file, first write a JSON file containing one object per row, keyed by the header line's names. Use a CSV parser rather than splitting on commas, since a quoted field can hold a comma, and leave an empty field's key out of its object, so its column takes NULL. Then pass the JSON file to the script; the script itself reads JSON only.
- Once production has started a version that carries the file, never edit the file. Put a later fix in a new file, as step 4 (Keep the schema as migrations) of Add a database says.
- The Database package's test double, the stand-in database your tests use, applies the file too when it is created. Its
reset()empties the tables again. - The 512 KiB per-file limit applies to inline
deploy_filesentries. For larger records, split them across numbered files, use a stored entry, or deploy withturnzero. With no shell, ask your user to upload a file you cannot read and use a stored entry. The 4 MiB total and 200-entry limits still apply. - The sample gives imported rows new numeric IDs. To preserve existing numeric IDs, include
idwith its matching numeric type in the third argument, then advance the table's sequence past the imported IDs in the same migration file. Text IDs need a text column and no sequence, as the example below shows.
Keep original text IDs #
For text IDs, use a matching text column rather than a sequence. For a new database, this is an alternative to the bigserial table in Add a database. Put the table definition in the schema migration before the import:
CREATE TABLE notes (
id text PRIMARY KEY,
title text NOT NULL
);
Then a later import migration can preserve IDs such as note-red and draft-42b:
INSERT INTO notes (id, title)
SELECT id, title
FROM jsonb_to_recordset($rows$[
{"id":"note-red","title":"First note"},
{"id":"draft-42b","title":"Draft note"}
]$rows$::jsonb) AS r(id text, title text);
Run the writer script above with node scripts/write_import_migration.mjs data/notes.json notes "id text, title text". The third argument, id text, title text, names the columns and their types. Both IDs are kept exactly; no sequence is created or advanced. Application code must also accept and generate text IDs. A missing or duplicate ID fails the import and rolls back that migration.
For an existing table with a different ID type, first write a schema migration that accounts for its data and any references to those IDs. Once production has started a version that carries a migration, never edit that file. For a migration recorded only in development, follow Add a database before changing it and clearing the development database. This example creates a new text-ID table; do not run its CREATE TABLE against a table that already exists.
Records with other fields #
If your records hold id, text and created, such as {"id":"note-red","text":"First note","created":"2026-01-05T09:30:00Z"}, put a table with those columns in the schema migration before the import:
CREATE TABLE notes (
id text PRIMARY KEY,
text text NOT NULL,
created timestamptz NOT NULL
);
Then the import migration names the three columns in each list, and gives their types in r(...):
INSERT INTO notes (id, text, created)
SELECT id, text, created
FROM jsonb_to_recordset($rows$[
{"id":"note-red","text":"First note","created":"2026-01-05T09:30:00Z"},
{"id":"draft-42b","text":"Draft note","created":"2026-01-06T14:00:00Z"}
]$rows$::jsonb) AS r(id text, text text, created timestamptz);
Run the writer script above with node scripts/write_import_migration.mjs data/notes.json notes "id text, text text, created timestamptz". The third argument is id text, text text, created timestamptz. A created value in ISO 8601 form, such as 2026-01-05T09:30:00Z, reads as a timestamptz. Like the text-ID example, this creates a new table; do not run its CREATE TABLE against a table that already exists.
A complete CommonJS server #
Use this server with the id, text and created table above. Save that table definition as migrations/0001_notes.sql, then run the writer script above with node scripts/write_import_migration.mjs data/notes.json notes "id text, text text, created timestamptz". Keep the generated import file in migrations/ beside the schema file.
Save the complete file below as src/server.cjs. Keep the application's dependencies, add express and pg, and set its start script to node src/server.cjs. The .cjs extension works with either package type.
Start from the application's root folder, which contains migrations/. For a local run, follow Run against your own PostgreSQL, including both database settings and loading .env. On the platform, declare the database in the manifest; its settings reach the running server automatically.
// src/server.cjs: Express with text-ID records and startup migrations, using pg alone.
const express = require('express');
const pg = require('pg');
const { readdir, readFile } = require('node:fs/promises');
const { join } = require('node:path');
// The Database package's ledger and lock, so its applyMigrations can take over later.
const LEDGER = 'schema_migrations';
const LOCK = "hashtext('mark_one_database_migrations')";
async function migrate(client, folder = 'migrations') {
// One client, not a pool: an advisory lock belongs to the connection that takes it.
await client.query(`SELECT pg_advisory_lock(${LOCK})`);
try {
await client.query(`CREATE TABLE IF NOT EXISTS ${LEDGER} (name text PRIMARY KEY, applied timestamptz NOT NULL DEFAULT now())`);
const { rows } = await client.query(`SELECT name FROM ${LEDGER}`);
const applied = new Set(rows.map((row) => row.name));
const names = (await readdir(folder)).filter((name) => name.endsWith('.sql')).sort();
for (const name of names) {
if (applied.has(name)) continue;
// Remove leading whitespace, including a byte-order mark, before running the migration.
const sql = (await readFile(join(folder, name), 'utf8')).trimStart();
// Each file and its ledger row in one transaction, so a failed file records nothing.
await client.query('BEGIN');
try {
await client.query(sql);
await client.query(`INSERT INTO ${LEDGER} (name) VALUES ($1)`, [name]);
await client.query('COMMIT');
} catch (error) {
await client.query('ROLLBACK');
throw error;
}
}
} finally {
await client.query(`SELECT pg_advisory_unlock(${LOCK})`);
}
}
// A request's abort signal. The deployed runtime attaches its own signal to each
// request, and it aborts at the request's window. A local run has none of its own,
// and Node's request.signal can abort at a normal request end on some Node 24
// releases, so a local run's signal aborts when the response closes unfinished.
function abortSignalOf(request, response) {
const own = Object.hasOwn(request, 'signal') ? request.signal : undefined;
if (own) return own;
const controller = new AbortController();
response.once('close', () => {
if (!response.writableFinished) controller.abort();
});
return controller.signal;
}
async function main() {
const url = process.env.APP_DATABASE_URL;
if (!url) throw new Error('APP_DATABASE_URL is not set');
const directUrl = process.env.APP_DATABASE_DIRECT_URL;
if (!directUrl) throw new Error('APP_DATABASE_DIRECT_URL is not set');
const limit = process.env.APP_DATABASE_CONNECTION_LIMIT ?? '';
const max = /^[1-9][0-9]*$/.test(limit) ? Number(limit) : 1;
const pool = new pg.Pool({ connectionString: url, max, connectionTimeoutMillis: 5_000 });
pool.on('error', (error) => console.warn('database session ended:', error.message));
const lostCodes = ['ECONNREFUSED', 'ECONNRESET', 'ETIMEDOUT', 'EAI_AGAIN', '57P01', '57P03', '08006'];
const deadline = Date.now() + 120_000;
try {
for (;;) {
try {
const client = new pg.Client({ connectionString: directUrl, connectionTimeoutMillis: 5_000 });
try {
await client.connect();
await migrate(client);
} finally {
await client.end();
}
break;
} catch (error) {
const lost = lostCodes.includes(error.code) || /timeout|terminated/i.test(error.message);
if (!lost || Date.now() + 1_000 > deadline) throw error;
await new Promise((resolve) => setTimeout(resolve, 1_000));
}
}
} catch (error) {
await pool.end();
throw error;
}
const app = express();
app.use((request, response, next) => {
// End the response when the request is aborted (abortSignalOf, above).
const signal = abortSignalOf(request, response);
signal.addEventListener('abort', () => response.destroy(), { once: true });
next();
});
const send = (response, status, body) => {
if (!response.destroyed) response.status(status).json(body);
};
app.get('/health', async (_request, response) => {
try {
await pool.query('SELECT 1');
send(response, 200, { ok: true });
} catch (error) {
console.error(error);
send(response, 503, { ok: false });
}
});
app.get('/notes', async (_request, response) => {
try {
const { rows } = await pool.query('SELECT id, text, created FROM "notes" ORDER BY id');
send(response, 200, rows);
} catch (error) {
console.error(error);
send(response, 500, { ok: false });
}
});
app.use((_request, response) => send(response, 404, { error: 'not_found' }));
const port = Number(process.env.PORT ?? 8080);
app.listen(port, () => console.log(`listening on ${port}`));
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});
The server applies missing migration files before listening. It uses one direct connection for the migration lock and a separate pool for requests. It retries connection failures during startup for up to 120 seconds; other failures end startup without listening.
GET /notes returns the imported text IDs, text and creation times. GET /health returns 200 after a successful database read, or 503 when that read fails. The request pool follows APP_DATABASE_CONNECTION_LIMIT, using one connection when the setting is absent or invalid.
Each migration and its ledger entry commit together. A restart skips files already recorded in schema_migrations, so it imports no record twice. This helper keeps no content hashes; never edit a file after production records it. Add a new migration instead.
Keep your application's authorization checks on its record routes. This example checks no caller; step 4 (Create, declare, and deploy) explains the manifest's required audience and sign-in.
Moving from Supabase #
Before importing, check the destination’s PostgreSQL major version. For a dump from a newer server, try a schema-only import in a disposable database on the destination version first.
A PostgreSQL restore brings over the database objects and rows in the dump. Sign-in and Supabase's browser Data API are separate services. Check the deployed app's browser and backend requests for calls to the old Supabase project. Decide which calls to replace and which to keep during the move. For users who will sign in on Turn Zero, follow Bring your existing users.
Check what the dump contains before rehearsing the restore. Include the application tables and the old account IDs and verification history needed for linking. Check for policies that name Supabase roles or use auth.jwt(), and for foreign keys to Supabase Auth tables. The application's database role must be able to load the objects you keep. The restore flags that omit ownership and grants leave those policy and foreign-key references in place.
For a foreign key to auth.users, point the key at a table your app owns and keep the old UUIDs for the referenced accounts. Load those UUIDs before loading rows that reference them. Replace the Supabase role names in policies with the destination application's database role where it needs that access. Keep the operations and row checks the policy allows. Where a check reads Supabase claims through auth.jwt(), use the verified session and your app's access records to enforce the same rule.
Create the auth.uid() helper before you restore or create any policy that calls it. For a reviewed schema followed by a data-only load, put the helper in that schema and load the data after creating the schema. Use Keep Supabase row policies for the helper, table settings and transaction code.
For policies that compare old Supabase user IDs, check the old account's eligibility and ownership before saving a link. On every request, verify the Turn Zero session, look up the saved link, and check the account's current permissions before querying. Follow Save the link and check permissions.
After sign-in, the verified session gives your backend the person's Turn Zero user ID. Use it to find their saved link and set app.user_id to the linked account's old Supabase UUID. The first sign-in can save that link using a verified email address when it meets the matching rules in the user guide. Leave the imported rows closed if the link or permission is missing.
With this link, imported rows and foreign keys can keep their Supabase UUIDs. Rehearse with two users in development. Check that the first sign-in saves each link, the second reuses it, and each user can reach only their own old rows.
The application’s database role cannot install supabase_vault, pg_cron or pg_net here. Remove those extension declarations and replace their uses before importing the dump.
- For
supabase_vault, use a stored secret from your backend. - For
pg_cron, use a scheduled job. - For
pg_net, make the request from your backend through a declared upstream.
Rehearse a private notes restore #
Use an empty development database and two test users. The example starts with private_notes(id, owner_id, body). Its owner_id refers to auth.users(id). The read and update policies apply to Supabase's authenticated role and compare owner_id with auth.uid().
Inspect the source. Check both PostgreSQL versions. Read the old table, foreign key and policy definitions before you import anything. Export the notes, the corresponding old account UUIDs, and the verification history and current access rules you need to link the users. Keep the account evidence in a separate, private export. Leave out old passwords, session tokens and service keys.
Prepare the target. Replace the reference to
auth.userswith an app-owned table for the old UUIDs. Keepowner_idand its values. Create theauth.uid()helper before creating policies that call it. Use the destination application's database role in the policies in place ofauthenticated.Load the old IDs first. Save the example as
restore-private-notes.sqland run it as the development application's database role. The sample includes two synthetic users and notes. For a rehearsal with your own test export, substitute your reviewed data rows for the two inserts, in the same order. Stop if the target already has these objects or if a note's owner is absent from the export.
BEGIN;
CREATE SCHEMA auth;
CREATE FUNCTION auth.uid() RETURNS uuid
LANGUAGE sql STABLE
AS $$ SELECT NULLIF(current_setting('app.user_id', true), '')::uuid $$;
CREATE TABLE public.legacy_supabase_users (
id uuid PRIMARY KEY
);
CREATE TABLE public.private_notes (
id uuid PRIMARY KEY,
owner_id uuid NOT NULL REFERENCES public.legacy_supabase_users (id),
body text NOT NULL
);
INSERT INTO public.legacy_supabase_users (id) VALUES
('11111111-1111-4111-8111-111111111111'),
('22222222-2222-4222-8222-222222222222');
INSERT INTO public.private_notes (id, owner_id, body) VALUES
('aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', '11111111-1111-4111-8111-111111111111', 'First test note'),
('bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb', '22222222-2222-4222-8222-222222222222', 'Second test note');
CREATE POLICY private_notes_read ON public.private_notes
FOR SELECT TO CURRENT_USER
USING (owner_id = auth.uid());
CREATE POLICY private_notes_update ON public.private_notes
FOR UPDATE TO CURRENT_USER
USING (owner_id = auth.uid())
WITH CHECK (owner_id = auth.uid());
ALTER TABLE public.private_notes ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.private_notes FORCE ROW LEVEL SECURITY;
COMMIT;
Run the script from the folder holding your provisioned development settings. On Windows PowerShell use turnzero.cmd and psql.exe. See Connect to your database for prerequisites.
turnzero db connect --environment development -- psql --no-psqlrc --set ON_ERROR_STOP=on --file restore-private-notes.sql
Use the saved link. Follow Bring your existing users to verify the Turn Zero session, link each eligible account and reuse the link on later requests. Keep the new-to-old mapping separate from the UUID table above. If verification, linking or current permission fails, stop before querying the notes.
Check the requests. Replace the browser's Supabase requests with your backend's read and update routes. Set
app.user_idto the saved old UUID in each database transaction. Use that same transaction for its query. In the update route,noteIdandbodyare validated inputs.legacyUserIdcomes from the backend's verified link.
await tx.query("SELECT set_config('app.user_id', $1, true)", [legacyUserId]);
const { rows } = await tx.query(
'UPDATE public.private_notes SET body = $1 WHERE id = $2 RETURNING id, body',
[body, noteId],
);
Commit a successful transaction and roll it back if a query fails. Treat an empty update result as no note found for that user. In development, sign in twice as each test user. Confirm each returns to the same old account and can read and update only their own note. Try the other note's ID, a request without a link, and a database transaction without app.user_id. None should return a private note. Compare the old and new owner UUIDs and check that the browser now calls your backend.
Copy private note attachments #
Use this part if your app keeps files in Supabase Storage. If your app has no stored files, skip it.
Continue the private notes rehearsal in development. Use the same two test users and notes. In the old Supabase project, use one private bucket called note-attachments. Keep one small text file per note. Give the two files different contents so a crossed link is easy to spot.
Make a private copy list. For each file, record its old bucket and object path, the note ID, the note owner's old UUID, and the file's content type. Compare the bucket's read rules with the note's owner before copying. Stop on a missing note, an unknown owner or an ambiguous match. Download the two files through your authorized Supabase export or admin access. Keep the files, copy list and source credential out of the app folder, Git and logs.
Set up the destination. Add
{"name":"note-attachments","account_keyed":true}toareasin the app's storage declaration. Keep the other areas and services. Submit the full manifest and checkstorage_areasfornote-attachmentswith outcomecreatedorunchanged. The owner check in step 4 keeps each file private. Use the same saved links from the notes rehearsal to find each owner's Turn Zero development user ID. Name each file<turn-zero-user-id>/<note-id>/attachment.txt. Keep the old path and the new file name together in your private copy list.Copy the files. Use a private copy script with the application's development platform credential in
TURNZERO_CLOUD_APP_TOKEN. It selects development, so leave out the environment header. Keep the credential outside the app folder and out of Git and logs.For each file, write its bytes to the area with the original content type,
If-None-Match: *and anX-Acting-Identitysuch asnotes-migration. That header records who made the copy. Access still depends on the app's own checks. If a destination file already exists, compare its contents with the source before treating it as copied. Stop and inspect any difference. Read each copy back and compare its bytes and content type.Keep the note's link working. Serve the attachment through the app, for example at
/api/notes/<note-id>/attachment. Replace direct Supabase links in the app with this route. If the app already has its own attachment URLs, keep routing them through the same owner check. Old Supabase URLs still point to the old service.Verify the caller's session, look up their saved old UUID, and check the account's current permissions. If any check fails, stop before querying the note. Read the note using the owner policy from the restore. If it returns no row, stop before reading Storage. Build the file name from the verified user ID and the note ID you read. Accept no storage path or owner ID from the browser.
To make the browser download the file, send
Content-Disposition: attachmentandX-Content-Type-Options: nosniff, as in the signed-in download example.Check both users. In one development trial, open each note's link as its owner and compare the downloaded bytes and content type with the source. Swap the links between users, then try one signed out and one with no saved link. Each of those requests must return no attachment. Confirm the browser uses the app's link and receives no storage credential. Repeat the copy to check that existing files are left in place. Keep old storage in service until you have checked the new links.
Port one edge function #
Use this part if your app has Supabase edge functions. If it has none, skip it.
Continue the private notes rehearsal in development with the same two test users. Port list-notes, the Deno.serve function that forwards the caller's Supabase token and reads id, body from private_notes.
Turn Zero also runs functions on Supabase Edge Runtime. Put the new handler in functions/api/notes.js. Its default export has a fetch(request) method that returns a Response for /api/notes.
List @turnzero/account and pg in package.json. Keep database and accounts in the manifest. Read settings from process.env. Remove SUPABASE_URL, the Supabase anon and service keys, and Supabase token forwarding from this route.
Reuse the session reader in lib/session.js to verify the Turn Zero cookie or bearer token. In lib/private-note-access.js, have allowedLegacyUserId use the saved link and current permissions. It returns the saved old UUID if both checks pass and null otherwise.
Use APP_DATABASE_URL and keep one connection per worker, as in the example's lib/db.js. Set app.user_id and read the notes in the same transaction. The restore's auth.uid() helper uses that setting to apply the owner policy.
import pg from 'pg';
import { createUserReader, openLiveAccounts } from '../../lib/session.js';
import { allowedLegacyUserId } from '../../lib/private-note-access.js';
const connectionString = process.env.APP_DATABASE_URL;
if (!connectionString) throw new Error('APP_DATABASE_URL is required');
const pool = new pg.Pool({ connectionString, max: 1 });
const readUserId = createUserReader(openLiveAccounts);
export default {
async fetch(request) {
if (new URL(request.url).pathname !== '/api/notes') {
return new Response(null, { status: 404 });
}
if (request.method !== 'GET') {
return new Response(null, { status: 405, headers: { Allow: 'GET' } });
}
const userId = await readUserId(request);
if (userId === null) return new Response(null, { status: 401 });
const legacyUserId = await allowedLegacyUserId(userId);
if (legacyUserId === null) return new Response(null, { status: 403 });
const tx = await pool.connect();
let discard = false;
try {
await tx.query('BEGIN READ ONLY');
await tx.query("SELECT set_config('app.user_id', $1, true)", [legacyUserId]);
const { rows } = await tx.query('SELECT id, body FROM public.private_notes');
await tx.query('COMMIT');
return Response.json(rows, { headers: { 'Cache-Control': 'no-store' } });
} catch {
try {
await tx.query('ROLLBACK');
} catch {
discard = true;
}
return new Response(null, { status: 500 });
} finally {
tx.release(discard);
}
},
};
Point the browser at /api/notes. In development, check that each test user sees only their own note. Check that a signed-out request returns 401 and that a signed-in account with no saved link gets no rows.
Replace calls to the Supabase client library #
If a browser uses @supabase/supabase-js, list the calls it makes. Replace each call you plan to move with a call to your application's backend. A route on your server or a function under functions/ can handle one operation, such as listing the signed-in user's notes.
- For reads and writes through
.from(), call your own route and run a parameterized query in the backend. Connect using your app's database settings and keep the connection string on the backend. - For calls through
.rpc(), give each database action you use its own backend route. Check the inputs and permissions there before calling the database function. - For sign-in and the current user, follow Add sign-in to your app. The backend verifies the session before using the user ID or looking up a saved link.
- For file uploads and downloads, use Storage from your backend. Check who may read or change each file.
- Supabase Realtime subscriptions have no direct replacement. If users need updates, choose how your app will refresh or deliver them before removing the old subscription.
For example, replace supabase.from('private_notes').select('id, body') with a browser request like fetch('/api/notes'). Have the route verify the session, check permission and return the rows that user may read. Keep the response fields the page uses. The row-level security example shows where to set the user ID before querying.
Test the new calls in development with two users. Check both successful requests and requests that should fail. In your browser's network panel, confirm that the calls you replaced go to your app's routes.
4. Create, declare, and deploy #
The manifest's audience is required and has no default. Choose it before the manifest is written (Choose who may sign up). Your AI coding agent uses the audience stated in your project, including its README. A team, company or invited group means invited; visitors, customers or the public mean public. It chooses workforce only when the project names the identity provider's tenant.
With no audience stated and a person present, it asks once whether anyone may use the application or only people you invite. If you do not answer, it chooses public. With nobody to ask and no audience stated in the project, it chooses and reports public, except invited for a server without its own sign-in. It explains that the server checks no caller and how to open access.
For a static site with no audience stated and nobody to ask, it chooses public and reports that anyone can reach it. It says how to restrict it: set the manifest's audience to invited, call submit_manifest, and deploy as required.
An invited audience requires sign-in and admits new users only by invitation. For callbacks from other services, your AI assistant lists their paths in session_free_paths and checks that each route verifies the sender (Choose who may sign up). You can change the audience later by editing the manifest and calling submit_manifest again.
For an internal tool with no sign-in of its own, choose invited: the platform signs people in before they reach the tool, and you invite each person. Use public when anyone may reach the tool and its backend controls access to data.
For a server, use the application you created for the restore if you already did that step. Otherwise, call create_application with the size you chose, as Create the application describes. Submit the manifest if you have not submitted it or it has changed. For static files alone, follow Publish a static site. Use kind: "serverless" and omit size. Upstreams, sign-in, and push notifications go in their own entries of the manifest (Author the manifest).
For complete server manifests with health and packages, see A manifest that works.
After submitting the manifest, your AI assistant calls check_deploy before the first deploy. It resolves any platform readiness refusals before proceeding. It can also run the separate, optional file check described there.
Your AI assistant then deploys as Build and upload the artifact describes. If the manifest declares a database, or the application has a web client, it first reads that part of the deploy skill. It makes one deploy_command call and runs the returned command if it can. A hosted connection can return no command even when the assistant has a shell. If there is no command it can run, it follows the returned fallback and uses deploy_files within its limits. If the command returns before the outcome, it calls read_status with wait_seconds.
If development is on, verify the changed routes there. Promote only after the owner asks for or approves it. If another deploy could change what development serves, give promote the version you tested. Use wait_seconds as Promote to production describes.
Until the environment's first deploy records deployed, requests to its hostname return 404 not_deployed, including requests to the health path. This is expected.
Move data and traffic to the new server #
If people already use the old application, agree with the owner on when to pause writes, restore production data and switch traffic. Keep the old app and its route available until the new one passes the checks below.
Adapt each scheduled command before you copy its timetable. Move short work into a private schedule handler. In development, verify the result for the intended hour or work ID.
Rehearse on development data. Restore a test dump and check the app at its development hostname. Check key pages and API routes, sign-in, redirects and cache headers. Check mail with a test address and schedules with safe test data. Leave mail-sending schedules off until you check that the restored records and the mail settings send every rehearsal message only to test addresses you control.
For a Netlify move, test the exact redirects and the rewrites your app handles. If you moved to a serverless app, also test page paths with no matching file or function. Check that Turn Zero serves the expected not-found page or root page.
Prepare the production target. Have the owner approve a production deploy or promote before you do it. Confirm that the target database exists and agree how to load the dump without duplicating or overwriting data you need. A promote leaves development data in development.
Choose and rehearse the restore before the first production deploy or promote. That release creates the production database. The server's startup migrations can create its tables before you connect. If startup already created a matching schema, rehearse a data-only load that preserves its migration history. If you need a full restore, rehearse it in an empty schema and agree with the owner how to prepare that target without losing data you need. After the release, check the actual tables and migration history before restoring anything.
Make sure the new copy starts without accepting live writes or running schedules that change data. Leave schedules that change data out of the submitted manifest until the hostname checks pass, then add them back, submit the manifest, and deploy to production or deploy to development and promote.
Make the final data copy. Pause writes on the old app at the agreed time.
Stop new runs from the old scheduler or workers and confirm any work in progress has stopped writing. Record the last completed scheduled run so you can check the first run on the new host.
Have the owner take a fresh PostgreSQL dump with
pg_dumpin their own terminal. If prompted, the owner enters the old database password there. Keep the password out of chat and command arguments. Ask the owner to approve the temporary production database connection in their browser. Restore the dump to the agreed target. Check the restore result and compare counts and known records with the old database at the time of the dump.For a Netlify move, check that forms, browser calls to a separate data service, and scheduled or background functions have stopped writing before the final dump.
For a custom archive,
pg_restoredisables its session's statement timeout and the production connection still ends at the deadlineturnzero db connectprints. A restore that drops tables can wait on open transactions, so agree with the owner when the target app and its jobs will stop using the database, then check their access after the restore.Check the new production copy. Before changing traffic, check the new app at its Turn Zero hostname. Verify the key pages, API responses, sign-in, redirects and cache headers. Confirm the mail settings. Use
cron_previewto check the planned times for schedules already declared. For a schedule you add back in step 5, check its planned times in the manifest submission response before the deploy or promote that starts it. Keep live writes paused until the new copy is ready.Move the hostname separately. Get the owner's approval for the switch. Save the previous DNS records and keep the old host available. Follow Attach your own domain for the records to change. Review sign-in callbacks and passkeys before switching. Once the hostname serves, check HTTPS, sign-in and key routes there. Resume writes on the new copy only after those checks pass. Once the owner approves starting the timetable, check its first actual run and the result it saved.
If Netlify serves a bare domain and a subdomain, choose the subdomain to attach and agree how the bare domain will forward before changing DNS.
If
read_statusalready lists the TXT record, have the owner add it before changing the CNAME and allow for the custom hostname to be unavailable until the state isserving. After you resume writes on the new app, keep the old app read-only while requests still reach it through cached DNS records.
If a check fails before the switch, keep traffic on the old host. If it fails after the switch, agree with the owner how to return traffic and preserve any new writes before changing the route back.
Move a Netlify form #
This example moves a public contact form that saves one message. Keep the form's original access rules if it takes private submissions. Start with the functions and database example, which includes a manifest that declares a database and a root package.json that installs pg.
Turn Zero's per-address request limit for visitors without a valid session is the form's only rate limit. If a page shows a saved message, escape it before putting it into HTML so it appears as text.
1. Point the form at your function #
In the built page, such as client/index.html, replace the Netlify form settings with method="post" and action="/api/contact". Keep the label and make the input name match the name the function reads. A static file at /api/contact would answer GET and HEAD before the function, so keep static files on other paths.
<form method="post" action="/api/contact">
<label for="message">Message</label>
<textarea id="message" name="message" maxlength="1000" required></textarea>
<button type="submit">Send</button>
</form>
2. Create a table for submissions #
Save the SQL as migrations/0002_contact_submissions.sql if you started with the example. If your app already has migrations, give it the next number. The platform applies the migration before the new version serves.
CREATE TABLE contact_submissions (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
message text NOT NULL CHECK (char_length(message) BETWEEN 1 AND 1000)
);
3. Store the POST and check that it arrives #
Save the function as functions/api/contact.js. It opens at most one database connection per worker. It validates the form in the backend and redirects to the home page after the insert succeeds. The browser and function count UTF-16 units, so an emoji can take more than one of the 1,000 units.
import pg from 'pg';
const pool = new pg.Pool({
connectionString: process.env.APP_DATABASE_URL,
max: 1,
connectionTimeoutMillis: 5000,
});
pool.on('error', (error) => console.error(error.message));
export default {
async fetch(request) {
if (request.method !== 'POST') {
return new Response('Use POST', { status: 405, headers: { Allow: 'POST' } });
}
const contentType = request.headers.get('content-type') ?? '';
if (contentType.split(';')[0].trim().toLowerCase() !== 'application/x-www-form-urlencoded') {
return new Response('Send a form', { status: 415 });
}
let form;
try {
form = await request.formData();
} catch {
return new Response('Could not read the form', { status: 400 });
}
const field = form.get('message');
const message = typeof field === 'string' ? field.trim() : '';
if (!message || message.length > 1000) {
return new Response('Enter a message of up to 1000 characters', { status: 400 });
}
await pool.query('INSERT INTO contact_submissions (message) VALUES ($1)', [message]);
return new Response(null, { status: 303, headers: { Location: '/' } });
},
};
Deploy to development and send a test message from the form. Check its saved row with Read your data. Send a POST to /api/contact with content type application/x-www-form-urlencoded and body message=. Use write_route from a chat or send the request from your terminal. Check for a 400 response and confirm that no row was saved.
Move an Express notes app to functions #
Use this example when you have chosen to replace the Express backend with functions. The new serverless application keeps the public notes frontend and replaces data/notes.json with PostgreSQL. Its frontend uses same-origin requests. Keep GET /api/notes, which returns { notes: [{ id, title }] }, and POST /api/notes, which accepts { title } and returns the saved note with status 201.
- Keep the frontend. Copy the built HTML, CSS and JavaScript into
client/without changing its relative API URLs. Keep the existing error handling and safe text rendering. Keep static files off/api/notesbecause a matching file takes precedence over the handler. - Create a separate application. Call
create_applicationwithkind: "serverless"and nosize. This example uses a public audience for public notes. Keep the checks and audience your original app needs when moving private data. - Prepare the database. Add the two migrations below. Use an export of the old file for development, then plan a final export with writes paused before moving real traffic.
The old file for this example contains these records:
[
{"id":"note-red","title":"Check the invoice"},
{"id":"note-blue","title":"Call the supplier"}
]
Save this manifest as manifest.json. Submit the complete file with submit_manifest:
{
"manifest_version": 1,
"services": [
{
"kind": "database"
}
],
"region": "usa",
"egress": [],
"audience": {
"kind": "public"
},
"packages": []
}
With a shell, install pg as a runtime dependency and keep the lockfile. Use an ES module package so that .js files can use import. This package.json uses the same pg version range as the functions-database example:
{
"name": "moved-notes",
"private": true,
"type": "module",
"dependencies": {
"pg": "^8.22.0"
}
}
Save migrations/0001_notes.sql. Old IDs stay as text, and the database assigns new IDs when inserting new notes:
CREATE TABLE notes (
id text PRIMARY KEY DEFAULT gen_random_uuid()::text,
title text NOT NULL CHECK (title <> '')
);
Save migrations/0002_import_notes.sql for the two example rows:
INSERT INTO notes (id, title) VALUES
('note-red', 'Check the invoice'),
('note-blue', 'Call the supplier');
For your own records, use the import script above with node scripts/write_import_migration.mjs data/notes.json notes "id text, title text" in place of typing the values. Check the record count, IDs and required fields first. Use a new numbered migration for any later import.
Save lib/notes.js. The function checks the method and the submitted title, and sends SQL values as parameters:
async function readTitle(request) {
const reader = request.body?.getReader();
if (!reader) return null;
const decoder = new TextDecoder('utf-8', { fatal: true });
let body = '';
let bytes = 0;
try {
for (;;) {
const { done, value } = await reader.read();
if (done) break;
bytes += value.byteLength;
if (bytes > 4096) {
await reader.cancel();
return null;
}
body += decoder.decode(value, { stream: true });
}
const { title } = JSON.parse(body + decoder.decode()) ?? {};
return typeof title === 'string' ? title.trim() : null;
} catch {
return null;
} finally {
reader.releaseLock();
}
}
export function createNotesHandler(query) {
return async function fetch(request) {
if (new URL(request.url).pathname !== '/api/notes') {
return Response.json({ error: 'not_found' }, { status: 404 });
}
if (request.method === 'GET') {
const { rows } = await query('SELECT id, title FROM notes ORDER BY id');
return Response.json({ notes: rows });
}
if (request.method === 'POST') {
const title = await readTitle(request);
if (!title || title.length > 200) {
return Response.json({ error: 'invalid_title' }, { status: 400 });
}
const { rows } = await query(
'INSERT INTO notes (title) VALUES ($1) RETURNING id, title',
[title],
);
return Response.json(rows[0], { status: 201 });
}
return Response.json({ error: 'method_not_allowed' }, {
status: 405,
headers: { allow: 'GET, POST' },
});
};
}
Save functions/api/notes.js to keep the same URL the frontend calls. The function opens at most one database connection per worker and reads the pooled address from APP_DATABASE_URL:
import pg from 'pg';
import { createNotesHandler } from '../../lib/notes.js';
let pool;
function query(sql, values) {
const url = process.env.APP_DATABASE_URL;
if (!url) throw new Error('APP_DATABASE_URL is not set');
pool ??= new pg.Pool({ connectionString: url, max: 1, connectionTimeoutMillis: 5000 });
return pool.query(sql, values);
}
export default { fetch: createNotesHandler(query) };
Deploy the contents of the new folder with the function deploy steps. Include manifest.json, package.json, the two migrations, client/, lib/notes.js and the function. Turn Zero applies migrations before the version serves, so there is no Express startup process or migration runner.
In the test environment, request / and GET /api/notes. Confirm your frontend still renders and the two original IDs and titles are present. Add a note from the existing frontend, refresh, and check it remains. Check that an empty title returns 400.
Before sending people to the new app, compare its notes with the final export. Keep the old app available while you verify the new one. Use a fresh target for the final export. If the target already has imported data, use a new migration to add, update or remove rows to match the export. Keep earlier applied migration files as they were.
Expected result #
The application runs at <label>.ai.host, as the Expected result of Deploy from your computer describes, and each key it uses is stored on the platform.
Refusals #
See the refusals reference for other platform errors.
| Refusal | Status | Cause | Remedy |
|---|---|---|---|
name_taken |
409 | create_application: the account already has a live application with that name. |
Choose another name; list_applications shows the application that has it. |
manifest_invalid |
400 | submit_manifest: the manifest breaks a rule of its format. The violations list shows the JSON path for up to 100 violations. When the check cuts a longer list short, detail says how many violations it left out. If the check limits the list to its first schema violation, detail explains why and omits the count. |
Correct each path against The manifest and submit the whole document again. |
setting_secret_missing |
409 | deploy or promote: a setting the manifest binds names a secret that is not stored for that environment. The detail names the setting and the secret, and next gives the store_secret call to make. |
Store the value with store_secret for the application and the environment, then deploy or promote again. |
Related #
- Deploy from your computer explains each step of a deploy.
- Store a secret stores the keys an application brought from elsewhere needs.
- Call an external API with an API key shows how an unchanged SDK reaches its API through the gateway.
- Test in development, then promote adds development and promotes a tested version.