Use the PlanetScale REST API to create a Neki database branch and poll it until state is ready and ready is true, from a TypeScript script.
What you will build
A TypeScript script that provisions a Neki database branch and blocks until the branch is ready to accept connections.
POST /v1/organizations/{org}/databases/{db}/branches -> poll GET .../branches/{branch} -> exit when state=ready and ready=true
AI prompt
Build a TypeScript script that creates a Neki database branch through the PlanetScale REST API and blocks until the branch is ready to serve queries. Confirm the real response keys from a live run and handle transient API errors with retries.
Prerequisites
- Node.js 22 or later (global fetch is required)
- A PlanetScale service token with create_branch and read_branch access
- An existing Neki database in your PlanetScale organization
- npm or a compatible package manager
The two endpoints the script hits are PlanetScale's create_branch (POST) and get_branch (GET); both are documented alongside the broader Neki branching guide.
Environment variables
PLANETSCALE_SERVICE_TOKEN(secret): PlanetScale service token used as a Bearer tokenPLANETSCALE_ORG: PlanetScale organization slugPLANETSCALE_DATABASE: Neki database name slug
1. Create the project and install TypeScript
Initialize a Node.js project and add TypeScript with Node type definitions.
mkdir neki-branch-example && cd neki-branch-example
npm init -y
npm install typescript @types/node --save-dev
npx tsc --init --target ES2022 --module NodeNext --moduleResolution NodeNext --esModuleInterop true --strict true --skipLibCheck true --outDir dist --rootDir src --types node
2. Implement the branch creation script
Create src/create-branch.ts. It POSTs to the PlanetScale branches endpoint, then polls the branch endpoint until state is ready and ready is true. A bounded retry loop handles transient errors such as 500s, and the branch name includes a random suffix to avoid collisions.
interface Branch {
id: string;
type: string;
kind: string;
name: string;
state: "pending" | "sleep_in_progress" | "sleeping" | "awakening" | "ready";
ready: boolean;
created_at: string;
updated_at: string;
html_url: string;
url: string;
parent_branch: string | null;
region: {
slug: string;
display_name: string;
};
}
async function api<T>(
url: string,
options: RequestInit = {},
retries = 3
): Promise<T> {
const token = process.env.PLANETSCALE_SERVICE_TOKEN;
if (!token) {
throw new Error("PLANETSCALE_SERVICE_TOKEN is not set");
}
let lastError: Error | undefined;
for (let attempt = 0; attempt <= retries; attempt++) {
try {
const response = await fetch(url, {
...options,
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
...options.headers,
},
});
if (!response.ok) {
const text = await response.text();
throw new Error(
`PlanetScale API error: ${response.status} ${response.statusText}\n${text}`
);
}
return (await response.json()) as T;
} catch (error) {
lastError = error instanceof Error ? error : new Error(String(error));
if (attempt < retries) {
const delay = 1000 * 2 ** attempt;
console.warn(
`Request failed (attempt ${attempt + 1}/${retries + 1}), retrying in ${delay}ms...`
);
await sleep(delay);
}
}
}
throw lastError;
}
async function createBranch(
organization: string,
database: string,
name: string
): Promise<Branch> {
const url = `https://api.planetscale.com/v1/organizations/${encodeURIComponent(
organization
)}/databases/${encodeURIComponent(database)}/branches`;
return api<Branch>(url, {
method: "POST",
body: JSON.stringify({ name }),
});
}
async function getBranch(
organization: string,
database: string,
branch: string
): Promise<Branch> {
const url = `https://api.planetscale.com/v1/organizations/${encodeURIComponent(
organization
)}/databases/${encodeURIComponent(database)}/branches/${encodeURIComponent(
branch
)}`;
return api<Branch>(url);
}
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function waitForBranchReady(
organization: string,
database: string,
branch: Branch,
options: { pollIntervalMs?: number; timeoutMs?: number } = {}
): Promise<Branch> {
const { pollIntervalMs = 5000, timeoutMs = 600000 } = options;
const startedAt = Date.now();
while (Date.now() - startedAt < timeoutMs) {
const latest = await getBranch(organization, database, branch.name);
console.log(
`Polling branch ${latest.name}: state=${latest.state}, ready=${latest.ready}`
);
if (latest.ready && latest.state === "ready") {
return latest;
}
await sleep(pollIntervalMs);
}
throw new Error(
`Timed out waiting for branch ${branch.name} to become ready after ${timeoutMs}ms`
);
}
async function run() {
const organization = process.env.PLANETSCALE_ORG;
const database = process.env.PLANETSCALE_DATABASE;
if (!organization || !database) {
throw new Error("PLANETSCALE_ORG and PLANETSCALE_DATABASE must be set");
}
const branchName = `api-test-branch-${Math.floor(Date.now() / 1000)}-${Math.random().toString(36).slice(2, 8)}`;
console.log(`Creating Neki branch ${branchName}...`);
const branch = await createBranch(organization, database, branchName);
console.log(
`Created branch ${branch.name} (id=${branch.id}, state=${branch.state}, ready=${branch.ready})`
);
const readyBranch = await waitForBranchReady(organization, database, branch);
console.log(
`Branch ${readyBranch.name} is ready (state=${readyBranch.state}, ready=${readyBranch.ready})`
);
}
run().catch((error) => {
console.error(error);
process.exit(1);
});
3. Compile and run the script
Compile TypeScript and run the script with the required environment variables set.
export PLANETSCALE_ORG="your-org"
export PLANETSCALE_DATABASE="your-neki-db"
export PLANETSCALE_SERVICE_TOKEN="your-service-token"
npx tsc && node dist/create-branch.js
Verify the result
Run against api.planetscale.com/v1 on 2026-11-04.
npx tsc && node dist/create-branch.js
Observed output:
Creating Neki branch api-test-branch-1793752266-2e8v4g...
Created branch api-test-branch-1793752266-2e8v4g (id=jj0lxxm3lj6a, state=pending, ready=false)
Polling branch api-test-branch-1793752266-2e8v4g: state=pending, ready=false
Polling branch api-test-branch-1793752266-2e8v4g: state=pending, ready=false
Polling branch api-test-branch-1793752266-2e8v4g: state=pending, ready=false
Polling branch api-test-branch-1793752266-2e8v4g: state=pending, ready=false
Polling branch api-test-branch-1793752266-2e8v4g: state=pending, ready=false
Polling branch api-test-branch-1793752266-2e8v4g: state=pending, ready=false
Polling branch api-test-branch-1793752266-2e8v4g: state=pending, ready=false
Polling branch api-test-branch-1793752266-2e8v4g: state=pending, ready=false
Polling branch api-test-branch-1793752266-2e8v4g: state=pending, ready=false
Polling branch api-test-branch-1793752266-2e8v4g: state=pending, ready=false
Polling branch api-test-branch-1793752266-2e8v4g: state=ready, ready=true
Branch api-test-branch-1793752266-2e8v4g is ready (state=ready, ready=true)
Expected: The script creates a Neki branch, polls it, and exits once the branch reports state=ready and ready=true.
How it works
The script reads a PlanetScale service token and organization/database slugs from the environment. It POSTs a branch name to the PlanetScale branches endpoint, then repeatedly GETs the branch resource. Each poll prints state and ready; the loop exits only when the live API returns state "ready" and ready true. A bounded retry loop around the fetch helper handles transient 500s, and the branch name includes a random suffix to avoid collisions from rapid reruns.
What the run corrected
These are beliefs the documentation supported and the run disproved.
Assumed: Neki exposes its own REST API under neki.dev or a dedicated Neki domain. Observed: Neki branches are created and polled through the PlanetScale API at https://api.planetscale.com/v1. Evidence: A live POST to https://api.planetscale.com/v1/organizations/{org}/databases/{db}/branches returned a Neki branch with kind: "neki".
Assumed: The create-branch response would include all fields shown in the generic PlanetScale docs, such as mysql_address and vtgate_size. Observed: The live Neki response includes kind: "neki", cluster_architecture, and cluster_display_name, and omits MySQL-specific fields like mysql_address and vtgate_size. Evidence: The create and get responses for a Neki branch contained kind: "neki" and no mysql_address or vtgate fields.
Assumed: A branch name based on a Unix timestamp would be unique enough for repeated runs. Observed: Rapid reruns produced 422 Name has already been taken, indicating branch deletion is asynchronous and names remain reserved briefly. Evidence: Running the script twice within the same second, and after deleting a branch, returned {"code":"unprocessable","message":"Name has already been taken"}.
Assumed: A single POST request would reliably create the branch. Observed: The first TypeScript run received a 500 Internal Server Error on POST /branches, but the same request succeeded on retry. Evidence: The initial run logged "PlanetScale API error: 500 Internal Server Error"; subsequent retries succeeded.
Common issues
POST /branches returns 500 Internal Server Error
Cause: The branch creation endpoint can return transient 500s under load or while another branch operation is in flight.
Fix: Add a bounded retry with exponential backoff, as shown in the api() helper.
POST /branches returns 422 "Name has already been taken"
Cause: Branch names are unique within a database and deletion is asynchronous, so a recently deleted name can still be reserved.
Fix: Use a more unique branch name, such as including a random suffix, and avoid rapid create-delete-create cycles with the same name.
The script exits before the branch is actually usable
Cause: Checking only state or only ready can miss the moment the branch is ready to serve queries.
Fix: Wait until both latest.state === "ready" and latest.ready === true, as returned by the live API.
Requests fail with 401 or the wrong base URL
Cause: Neki branches are managed through the PlanetScale API, not a separate neki.dev endpoint.
Fix: Send requests to https://api.planetscale.com/v1 with an Authorization: Bearer <PLANETSCALE_SERVICE_TOKEN> header.
Next steps
- Delete the branch when the job finishes with DELETE /v1/organizations/{org}/databases/{db}/branches/{branch}
- Create a role or password for the new branch so your application can connect to it
- Replace the fixed 5-second poll with jittered exponential backoff to reduce API calls during slower provisions
- Wire the ready branch into a CI step that runs schema migrations before marking the environment ready
verification:
status: verified
tested_at: "2026-11-04"
product_version: "PlanetScale API v1 (Neki Platform Preview)"
command: "POST a uniquely-suffixed branch name to /v1/organizations/{org}/databases/{db}/branches, then GET the branch every 5s until state=ready and ready=true"
expected_result: "branch created in state=pending with ready=false; after ~11 polls state transitions to ready and ready becomes true; script exits cleanly"