Build a mobile app's backend #
On this page
Prompt: paste this into your AI tool.
Build the backend for our iPhone and Android app on Turn Zero Cloud, with sign-in.
Also works: "Our Expo app needs a backend and user accounts." "Host the API our mobile app calls." "The app has no website, only the app." "Our Mac and Windows app needs sign-in."
Turn Zero Cloud hosts the backend, runs the sign-in, and checks each request before it reaches the backend. The mobile app itself is yours: you build and sign it with its own tools and ship it through the app stores.
Your AI starts by creating the backend, declaring the accounts service, and registering the mobile app's identifier and redirect URI. It then implements sign-in, authenticates requests, and checks compatibility before release. The eight steps below cover that complete workflow.
What your AI tool does #
- Reads the
mobile-backendskill withread_context, idskill:mobile-backend, or as the Model Context Protocol (MCP) prompt of that name. The skill gives the steps below in order, and its shortest path covers the common case: users who sign in through the realm, with no work accounts and no push. - Writes the app's sign-in into the app as one module.
- Asks you for the app's identifier before it declares the app on the realm, and for its app signing identities where passkeys or
httpsredirects are wanted.
What you need #
- The app's identifier in reverse-domain form, such as com.example.app.
- A development build of the app that you can run in a simulator, an emulator, or on a phone.
Before your AI starts #
For the AI tool: The checks and procedures below address you directly. When a step needs the person, tell them what to do and wait for their response.
- Check that your Cloud connection is signed in (Connect your AI assistant).
- Identify the sign-in methods the app should offer, such as the emailed code, Google, Sign in with Apple, or passkeys (Add sign-in to your app).
- Gather the app's redirect scheme and app signing identities (the iOS bundle identity or the Android signing identity) where passkeys or
httpsredirects are wanted.
Steps #
For the AI tool: Follow these steps after the checks above.
Steps 1 to 8 build the common case: a backend whose users sign in through the realm. Push notifications and work accounts follow them.
1. Create the application with no web client #
A web client is optional. The backend is ordinary Node.js code with one server that listens on PORT, as Deploy from your computer describes. With no web client, the artifact, the zip a deploy installs, has no client/ folder, and every request reaches the backend's own routes.
Create the application with create_application, choosing shared-0.5gb or shared-1gb as its size. A new application has only production, so the debug build and the store build both call <label>.ai.host. Once you turn development on with create_environment, the debug build calls <label>-dev.ai.host instead.
Use production alone by default while only debug builds exist. A development environment is optional: with production alone, a deploy releases the backend to installed copies without a promote. We recommend it before the first store build to keep testers on a separate user list and check backend changes before promoting them. Ask before turning it on unless the person has already asked for development or for the store build to be readied.
Prepare the backend now. No turnzero scaffold template is a mobile backend. Start from hello-world, or database-service if the backend keeps data; neither includes a web client. Add the accounts service and declare the clients in steps 2 and 3 before the first deploy.
2. Declare the accounts service #
Add the accounts service to the manifest's services, and submit the manifest with submit_manifest. Each environment then gets its own realm, its list of end users.
{
"manifest_version": 1,
"services": [{ "kind": "accounts" }],
"health": "/health",
"region": "usa",
"egress": [],
"audience": { "kind": "public" },
"packages": [],
"realm": {
"sign_in_methods": ["email"],
"clients": {
"production": [
{ "client_id": "com.example.app", "redirect_uris": ["com.example.app:/callback"] }
]
}
}
}
Keep the chosen sign-in methods in the manifest's realm.sign_in_methods, then submit the whole manifest. Use email for the emailed code. A new development realm starts with the default methods and applies the manifest's realm member. A choice made only with configure_app_sign_in on production does not carry over.
Where the manifest omits sign_in_methods, use configure_app_sign_in for each environment. The emailed code and passkeys work inside the app's browser sheet as they do on the web. For work accounts, Add work-account or Apple sign-in gives the redirect URI to register, and the worked example below joins the steps for one company's staff.
3. Declare the app on the realm #
The app is a client of the realm, known by its client_id and its redirect URIs. By default, declare it under clients in the manifest's realm member, with one list per environment, as step 2's sample shows. Use configure_app_sign_in only where the manifest lists no clients for that environment.
With one environment, declare the debug build on the production realm. The manifest's clients object takes a production array, a development array, or both. The example below shows the configure_app_sign_in alternative for production. Its clients field takes a single array. See Declare the client on each environment's realm for both forms.
Submitting a manifest's client list replaces that environment's list, including one set with configure_app_sign_in. Carry over every client with its redirect URIs and app identities; a client left out is no longer declared. Each client keeps its minimum_version and update_url by client_id; change those with configure_app_sign_in.
{
"application": "<application id>",
"clients": [
{ "client_id": "com.example.app", "redirect_uris": ["com.example.app:/callback"] }
]
}
This debug build has a custom-scheme redirect and no app signing identity. An app signing identity is the iOS bundle or Android signing identity that passkeys and app links use. Without one, the debug build signs in through the browser redirect alone, with no passkeys and no exchange of an Apple or Google sign-in token. To test those, declare the debug build's signing identity on the production realm. The platform then publishes that identity beside the store build's.
read_app_sign_in returns the declared clients. Declare the store build's redirect URIs and identities on the production realm too, before it ships. With development turned on, declare the debug build on the development realm instead, with environment: "development", and the store build on production's. Sign in from a native app covers the app signing identities, the three redirect forms, and the manifest's clients lists. A list in the manifest keeps the clients when the application is re-created or copied.
Submit and deploy the backend #
After declaring the accounts service and native clients, submit the whole manifest with submit_manifest. Deploy the backend as The deploy in one pass shows, and again after each change. Before a deploy to production, make the compatibility check in step 8. Once development is on, deploy to development and promote to production, as Test in development, then promote describes.
4. Sign in from a development build #
On one environment, a debug build and a store build both use the production hostname and sign in on production's realm. With development turned on, a debug build uses the development hostname, and a store build the production one. The sign-in runs in the system browser sheet. It uses the standard OAuth sign-in for apps: the authorization code flow with Proof Key for Code Exchange (PKCE). Expo Go's exp:// redirect is refused, so test in a development build with the app's own scheme.
Keep the flow in one module in the app's code. The module takes the app's browser sheet, secure store, random bytes, and SHA-256 as parameters. Where the app has its own fetch, the module takes that too. It imports nothing, so a test can run it with stand-ins (stubs).
Add the sign-in module gives the endpoint URLs and request fields for authorization, tokens, and revocation, plus the module and its Expo wiring. Each URL uses the hostname of the environment the build calls.
Where the app signs in with Apple's or Google's own software development kit (SDK) instead, it exchanges the provider's ID token at the realm's token endpoint for the same session. Step 10 (Sign in with Apple's or Google's own SDK) of Sign in from a native app covers that exchange.
5. Reach the backend from a simulator or an emulator #
Point the debug build at the production hostname, or at the development hostname once development is turned on. The iOS Simulator and the Android Emulator both reach it over the local computer's internet connection, as a phone does.
On one environment, the accounts testers sign in with are end users of the live application, on the same list as the app's real users. They have no tester marker. Ask the person for the testers' addresses and match them to the listed users. Turning development on gives testers a separate list. See List invitations and users.
Cloud hosts the sign-in pages, issues session tokens, and runs the account realm's endpoints. Starting your backend locally does not start local copies of those services. The Account client can verify sessions through Cloud's verification route. Verifying a token locally also requires the configured realm keys and the router's x-turnzero-cloud-session header, which records its verdict. See The router's session header.
For local backend work, the iOS Simulator reaches the local computer at localhost, and the Android Emulator at 10.0.2.2. See Sign in from a native app for the complete sign-in flow.
6. Call the backend with the bearer #
The app sends the session token as Authorization: Bearer <token> on every backend call, and the backend tells which user sent it as Tell which user sent a request shows. The platform refuses an expired or ended token with 401 before the request reaches the application's code. The backend's own 401 branch runs in the offline tests or in a local run, as Sign in from a native app says.
Check the bearer before anything else the route checks, such as whether its accounts client is set up, so a request with no bearer returns 401 in every run, never another check's 503.
7. Send the version header #
Send x-turnzero-cloud-client: <client_id>/<version>, such as com.example.app/1.0.0, on every call, and show the store link of a 426 response instead of retrying, as Keep installed clients compatible describes.
8. Read the versions in use before a release #
A deploy to production changes the backend every installed copy of the app calls, and so does a promote once development is turned on. First check that the store build is declared on the production realm. Then read the versions in use on that realm with read_app_sign_in.
A first store build needs no minimum_version or update_url. When an older build must stop, set them with configure_app_sign_in, never in the manifest, as Raise the minimum version describes.
Where the new backend drops something an installed version still calls, keep the backend compatible or raise the minimum first. Then deploy, or promote with promote once development is turned on.
Push notifications #
Where the app receives notifications, add {"kind": "push"} to the manifest's services, configure each provider with configure_push, and register each device after sign-in, as Send push notifications describes.
Worked example: a work-account mobile backend #
A backend that verifies the bearer and signs people in with one company's work accounts alone declares the workforce audience; one that also offers Google, GitHub, Apple, or the emailed code declares public. Sign in from a native app says what each audience does with a request that has no bearer. This example signs in one company's staff, so it declares workforce, and it joins the steps above into one setup in five parts.
Declare the backend and work-account sign-in #
The manifest declares the accounts service, the workforce audience, and the realm's work-account sign-in method. The audience names the company's tenant, its Microsoft Entra tenant ID. The realm member names entra in sign_in_methods. Its entra member has three required fields: tenant, the same tenant as the audience's; client_id, the app registration's client identifier; and client_secret_name, the stored client secret's name. The audience decides who may reach the backend, and the entra sign-in method signs them in.
{
"manifest_version": 1,
"services": [{ "kind": "accounts" }],
"health": "/health",
"region": "usa",
"egress": [],
"audience": { "kind": "workforce", "tenant": "00000000-0000-4000-8000-000000000001" },
"packages": [],
"realm": {
"sign_in_methods": ["entra"],
"entra": { "tenant": "00000000-0000-4000-8000-000000000001", "client_id": "00000000-0000-4000-8000-000000000002", "client_secret_name": "entra-client-secret" }
}
}
The deploy's own health check probes /health inside the platform. The workforce sign-in gate never refuses it, so the check needs no session_free_paths entry. Without that entry, your request from outside without a session receives 401 authentication_required, or the sign-in page in a browser. List /health there only for an outside probe without sign-in; that opens the path to everyone. See Choosing the health path.
Store the client secret #
Call store_secret with name: "entra-client-secret", the application, and the environment.
If the person deliberately put the secret in this conversation, pass it as value and omit value_file; the call stores it immediately. Otherwise, pass the supplied file's path as value_file, omit value, and run the returned command (Store a value from a file). Keep that file outside the application's folder.
Store the secret before submitting the manifest. If you stored it afterward, submit the manifest again so the realm receives it. Once development is turned on, repeat the storage step with environment: "development".
Declare native clients and register the callback #
Add the native clients to the realm member in the manifest above. Keep sign_in_methods and entra there. The production list holds the store build. If the app has development, put the debug build in development. On one environment, declare the debug build on production too.
Merge this clients object into realm and use your app's own IDs, redirect URIs and signing details. Include the development list when you want the debug client on that realm.
{
"realm": {
"clients": {
"production": [
{
"client_id": "com.example.app",
"redirect_uris": ["com.example.app:/callback"],
"ios": { "bundle_id": "com.example.app", "team_id": "ABCDE12345" },
"android": { "package": "com.example.app", "sha256_cert_fingerprints": ["AB:CD:..."] }
}
],
"development": [
{ "client_id": "com.example.app", "redirect_uris": ["com.example.app:/callback"] }
]
}
}
}
Call submit_manifest with the whole manifest. Add its realm.entra_callback to the company's app registration as a web redirect URI. Copy it exactly. The callback uses the platform's hostname, never the application's hostname. Both environments use the same callback, so add it once.
Where the manifest lists no clients for an environment, use the configure_app_sign_in alternative to set clients on that environment's realm.
Two reads check the setup before the first sign-in. read_app_sign_in on the environment returns the callback addresses, the declared native clients, and the work-account sign-in method with its client secret's name. list_secrets for that environment then shows whether that name is stored there. Where it was stored after the last submit_manifest, submit the manifest again so the realm receives it.
Before you set a minimum version for these clients, read Raise the minimum version for when the app shows the update screen and how to choose store links.
Read the work-account address #
Use the Account package by default; an empty packages list in a starter manifest does not choose the package-free route.
Before importing @turnzero/account, call read_library with entry: "account" and follow Use the library to run its returned take line at the project's root. Keep the package rows it writes when editing the manifest, and submit the updated manifest before deploying.
The backend verifies the session token through the verification route, with a client built without the realm's keys (Construction and options), because only that route returns the person's address. Your code reads the token from the Authorization header itself, because the client does not read request headers. A work-account user's address is marked source: "tenant". Its verified is true only where the tenant's token includes xms_edov as true and no other account already has the address verified. So add the optional claims email and xms_edov to the ID token in the registration's Token configuration (Add work-account sign-in).
For a package-free version, keep me.mjs and use the fetch-based server below. It calls the same verification route without importing the Account package.
Both versions here return only a verified tenant address; the general sign-in example accepts any verified address.
// me.mjs
export async function me(authorization, client) {
const token = authorization?.startsWith('Bearer ') ? authorization.slice('Bearer '.length) : null;
const verdict = await client.verifySession(token);
if (!('user' in verdict)) return { status: 401 };
const address = verdict.user.addresses.find((entry) => entry.source === 'tenant');
return { status: 200, id: verdict.user.id, email: address?.verified ? address.email : null };
}
Save the helper above as me.mjs and the server below as server.mjs. The server calls me for /me, uses its status as the HTTP status, and sends the remaining fields as JSON.
Keep the client setup in server.mjs so the offline test can import me without creating the client. makeVerifyClient throws when baseUrl is missing.
Run this server in a deployed copy or a provisioned local run, with TURNZERO_CLOUD_API set; the offline test imports me.mjs without server.mjs and needs no such setting.
// server.mjs
import { createServer } from 'node:http';
import { makeVerifyClient } from '@turnzero/account';
import { me } from './me.mjs';
const accounts = makeVerifyClient({ baseUrl: process.env.TURNZERO_CLOUD_API, credential: process.env.TURNZERO_CLOUD_APP_TOKEN });
createServer(async (request, response) => {
if (request.url === '/health') return response.writeHead(200).end();
if (request.url !== '/me') return response.writeHead(404).end();
const { status, ...body } = await me(request.headers.authorization, accounts);
response.writeHead(status, { 'content-type': 'application/json' }).end(JSON.stringify(body));
}).listen(process.env.PORT ?? 8080);
As Methods and results explains, verifySession returns user for a live session, { anonymous: true } when no session was supplied, or { refused, detail } for a refusal. The me helper returns HTTP 401 for the last two. For a live session, it returns the user's id and a verified tenant email address, or email: null if none is available.
Keep this example's HTTP 200 response with the user's id and email: null when the tenant address is unverified or missing. A valid session identifies the user without confirming an email address. Use the id to identify that user; do not rely on an unverified address to send mail or match accounts.
For a route that requires a verified address, return HTTP 403 when none is available. Reserve HTTP 401 for a missing or refused session, as the helper does. The platform supplies the address, its source, and its verified flag; your application decides which routes need a verified address.
Without the Account package: Save the file below as server-fetch.mjs, beside the same me.mjs helper. Use node server-fetch.mjs as the server's start command. It reads the same TURNZERO_CLOUD_API and TURNZERO_CLOUD_APP_TOKEN settings as the package example.
// server-fetch.mjs
import { createServer } from 'node:http';
import { me } from './me.mjs';
const accounts = {
async verifySession(session) {
if (!session?.startsWith('turnzero_cloud_usr_')) return { anonymous: true };
const answer = await fetch(`${process.env.TURNZERO_CLOUD_API}/accounts/v0/verify`, {
method: 'POST',
headers: { authorization: `Bearer ${process.env.TURNZERO_CLOUD_APP_TOKEN}`, 'content-type': 'application/json' },
body: JSON.stringify({ session }),
signal: AbortSignal.timeout(10_000),
});
const body = await answer.json();
if (answer.ok) return body;
// A refusal of the session carries cache_until. Any other is no verdict on the session.
if (body.cache_until) return { refused: body.error, detail: body.detail };
throw new Error(`verification route: ${body.error}`);
},
};
createServer(async (request, response) => {
if (request.url === '/health') return response.writeHead(200).end();
if (request.url !== '/me') return response.writeHead(404).end();
try {
const { status, ...body } = await me(request.headers.authorization, accounts);
response.writeHead(status, { 'content-type': 'application/json' }).end(JSON.stringify(body));
} catch (error) {
console.error(error);
response.writeHead(503, { 'content-type': 'application/json' });
response.end(JSON.stringify({ error: 'verification_unavailable' }));
}
}).listen(Number(process.env.PORT ?? 8080));
A refusal with cache_until means the session was refused, so /me returns 401. A failed verification call without that verdict returns 503. The shared me helper keeps the same user id and verified tenant address rules.
The app signs in with the module in Add the sign-in module. It sends the session token as Authorization: Bearer <token> on every backend call, as step 6 (Call the backend with the bearer) describes.
Test the signed-in route #
To test the signed-in route, ask a user of the company's tenant to sign in from a development build, as step 4 (Sign in from a development build) describes. You can also sign a test end user in using your AI tool's signed-in connection. That checks that the deployed gate accepts a signed-in request.
The me helper returns email: null for a test end user because that address has no source: 'tenant'. The scripted sign-in saves a session cookie, but me expects a bearer token. Read the session from the script's saved cookies (its cookie jar) and send Authorization: Bearer <session>. See Test a local run.
A job with only a minted token and no test_end_users grant can test only requests with no session (Choose the environment). Outside session_free_paths, a request with no session and no HTML Accept header gets the router's HTTP 401 (Public or workforce).
If the job's token has the grant, call request_route with test_end_user and session_as: "bearer". The platform sends the session as Authorization: Bearer with no cookie, so me returns 200 with the user's id and email: null. Leave out the authorization header: the platform supplies it. With session_as absent or set to cookie, the call sends a cookie and me returns 401.
To test me without a tenant user, use the Account package's test double offline. Build its client without realm keys, as this example does. Pass signIn a user with an address marked source: 'tenant', then send the returned session as a bearer token (Test with the double).
Save the following test as me.test.mjs, beside me.mjs.
// me.test.mjs
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { createAccountDouble } from '@turnzero/account/testing';
import { me } from './me.mjs';
test('GET /me answers a signed-in user and refuses no session', async () => {
const account = await createAccountDouble();
const client = account.client({ realmKeys: undefined, cacheSeconds: 0 });
const worker = account.signIn({ id: 'worker-1', addresses: [{ email: 'worker@contoso.example', verified: true, source: 'tenant' }] });
assert.deepEqual(await me(`Bearer ${worker.session}`, client), { status: 200, id: 'worker-1', email: 'worker@contoso.example' });
assert.deepEqual(await me(undefined, client), { status: 401 });
});
Expected result #
For the AI tool: Check these results before reporting success to the person.
The application runs with no web client. The app is declared on its realm, which is production's realm on one environment. In a development build, the sign-in opens in the browser sheet and returns to the app with a session. The backend answers the app's calls that carry the bearer token. Each response names the version that served it in the x-turnzero-cloud-version header.
Refusals #
This table lists the refusals these steps most often meet; the refusals page lists all of the platform's refusals, with the cause and remedy of each. A backend package's own failures are listed on its package page.
For the AI tool: Use the remedies below. Where a remedy needs the person, explain the next step to them.
| Refusal | Status | Cause | Remedy |
|---|---|---|---|
invalid_client |
400 | The client_id matches no client the environment's realm declares. |
Call read_app_sign_in for the environment whose hostname the build calls, and check that the client_id is among its clients. Add the client to the right list in realm.clients and call submit_manifest. With one environment, use production. A development list is checked at submission and takes effect when create_environment adds development. Use configure_app_sign_in where the manifest lists no clients for that environment. |
invalid_redirect_uri |
400 | The redirect URI is not declared, or is outside the three forms, such as Expo Go's exp://. |
Use a development build with the app's own scheme, and declare its URI. |
authentication_required |
401 | The bearer is expired, ended, or another realm's. | Refresh at the token endpoint, and sign in again where the refresh is refused. |
client_upgrade_required |
426 | The app's version is below its client's minimum on this realm. | Update the app from the store link, or lower the minimum. |
Related #
- Sign in from a native app details every sign-in request, the refresh, the sessions list, and deletion.
- Keep installed clients compatible covers the version header, the minimum, and the versions in use.
- Send push notifications covers the provider credentials, the device registration, and the send.
- Deploy from your computer covers the artifact, the deploy, and the promote.
- Manage end users lists every realm setting.