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."
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).
What your AI tool 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 tool 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 the choice and that it draws the account's Free Allowance.
A shared database is one monthly item for the application; 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 tool 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 tool: Check the following before starting.
- Your AI tool 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 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 answers 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 #
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 tool deploys holds package.json at its top. The deploy leaves out node_modules, .git, the AI coding tools' own files such as .claude and .mcp.json, and the .env and .env.* files, wherever they stand. 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 tool 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 tool moves each value the old host's environment held. It stores 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). - A value that is not secret, such as
SITE_TITLE, is not stored. It goes in the manifest'ssettingsas{"value": "<text>"}, the same 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 tool 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).
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.
3. Carry existing records into the database #
Skip this step where the application keeps no records in files.
Records the old copy kept in a file, such as 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. If it has no runner, add one from Keep the schema as migrations first; that section includes a runner using pg without the Database package. 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 carrying the file starts the application there. The platform does not perform the import itself. You need no separate production import command or production connection string.
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 text between two $rows$ quote tags, so no record needs escaping. 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, where migrations/ stands. 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.
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 tool 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 tool 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, your AI tool calls create_application with the size you chose and submits the manifest, as Create the application and Declare the manifest describe. For static files alone, it follows Publish a static site, using kind: "serverless" with no size. Upstreams, sign-in, and push notifications go in their own entries of the manifest (Author the manifest).
Your AI tool then deploys as Build and upload the artifact describes: one deploy_command call, the command it returns, and read_status with wait_seconds where that command returns before the outcome. If the manifest declares a database, or the application has a web client, your AI tool first reads the deploy skill's part for that. If your AI tool has no shell, it deploys through deploy_files instead. Where you turned development on, it moves the version to production through promote with wait_seconds, as Promote to production describes.
Until the environment's first deploy records deployed, its hostname answers 404 not_deployed, including the health path; this is expected.
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. violations lists the JSON path of each failing part. |
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.