---
title: Build a mobile app's backend
description: Run the backend of an iPhone or Android app with no web client, sign its users in from a development build, and keep installed versions working.
slug: /getting-started/build-a-mobile-app-backend
order: 9
visibility: public
redirects_from: [/getting-started/build-a-mobile-apps-backend]
---

# Build a mobile app's backend

Paste this prompt into your AI assistant.

> 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 and handles sign-in. Under an `invited` or `workforce` audience, the router requires a session on every route outside `session_free_paths`. Under a `public` audience, which the first example below declares, the router lets a request without a session through, so your backend checks who is calling before it serves a protected operation. You build and sign the mobile app with its own tools and ship it through the app stores.

**If you need one API route.** Start with [the backend choice](#1-create-the-application-with-no-web-client). An existing backend can serve the route without a website. For a protected action, [send and check the app user's session](#6-call-the-backend-with-the-bearer) before reading or changing their data. Try the route from a [development build](#4-sign-in-from-a-development-build) against the intended environment.

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.

To sign in one company's staff from a native app, start with the [work-account setup recipe](#worked-example-a-work-account-mobile-backend).

To add private photo uploads, follow [Upload a photo from a phone app](/cloud/guides/store-files/#upload-a-photo-from-a-phone-app) after you have native sign-in working.

<div id="what-your-tool-does"></div>

## What your AI does

- Reads the `mobile-backend` skill with `read_context`, id `skill:mobile-backend`, or as the Model Context Protocol (MCP) prompt of that name. The skill gives the steps below in order. Its shortest path covers users who sign in through the app's [realm](/cloud/concepts/glossary/#realm), which keeps its list of users. This path uses no work accounts or push notifications. If your app needs push notifications, choose a server backend at step 1 before creating the application.
- 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 `https` redirects are wanted.

## What you need

- The app's identifier in reverse-domain form, such as com.example.app.
- A [development build](/cloud/concepts/glossary/#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 assistant:** 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](/cloud/getting-started/connect-your-tool/)).
- 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](/cloud/guides/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 `https` redirects are wanted.
- Keep the backend in a separate project folder beside the Expo project, such as `backend/`. Run `turnzero scaffold --origin https://dev.turnzero.ai` and `turnzero library take --origin https://dev.turnzero.ai` from that backend project's root. Run `turnzero provision --origin https://dev.turnzero.ai` from the backend application folder with its `package.json` or `manifest.json`. In a scaffolded backend, that folder is `backend/app/`.

  Run `turnzero deploy --origin https://dev.turnzero.ai` there. For a functions-only backend with a root `functions/` folder and no `package.json`, use `turnzero` 0.59.12 or later. Without a terminal, use `tzcloud_deploy_files` with the [function files and manifest](/cloud/guides/deploy-functions/#deploy-the-handler). Keep these shell commands out of the Expo project root and its screens folder, such as `app/` or `src/app/`.

## Steps

**For the AI assistant:** 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. A serverless backend uses JavaScript functions under `functions/`, as [Deploy functions](/cloud/guides/deploy-functions/) describes. A server backend uses Node.js code listening on `PORT`, as [Deploy from your computer](/cloud/getting-started/deploy-an-application/) describes. Functions share a process with other customers' functions; a server has its own container. With no web client, the [artifact](/cloud/concepts/glossary/#artifact), the zip a deploy installs, has no `client/` folder. A backend that sends push notifications needs a server: the Push package is not proved in a function.

A new backend with one request-and-response route can use a function if it fits the function limits. If you keep starter code that listens on `PORT`, deploy it as a server. To use serverless for that route, move its handler into `functions/` and leave out the listening server.

Create the application with `create_application`. Choose `kind: "serverless"` and no `size` unless the backend needs something on the server list in [Choose the kind](/cloud/concepts/serverless-applications-and-servers/#choose-the-kind). For a server, ask an available person first and keep their chosen `size`, `shared-0.5gb` or `shared-1gb`. With no size chosen and nobody to ask, use Shared 0.5 GB. Report the size, that nobody was available, its awake-time charge and the option to request Shared 1 GB for more memory or CPU. A new application has production alone: debug and store builds call `<label>.ai.host`. After `create_environment` turns development on, debug builds call `<label>-dev.ai.host`.

Use production alone by default while only debug builds exist. A development environment is optional: with production alone, deploying releases the backend to installed copies of the app without a separate promotion. 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 --origin https://dev.turnzero.ai` template is a mobile backend. For a server, start from `server-hello`, or `server-database` if the backend keeps data; neither includes a web client. For functions, start from the handler in [Put the handler under functions](/cloud/guides/deploy-functions/#1-put-the-handler-under-functions). 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](/cloud/concepts/glossary/#realm), its list of end users.

```json
{
  "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 sample's `health` member for a server. A serverless application accepts the manifest with or without `health` and runs no health check.

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](/cloud/guides/add-work-account-or-apple-sign-in/#2-add-work-account-sign-in) gives the redirect URI to register, and the [worked example](#worked-example-a-work-account-mobile-backend) 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](/cloud/guides/sign-in-from-a-native-app/#1-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. Turn Zero keeps `minimum_version` and `update_url` for each matching `client_id`. Use `configure_app_sign_in` to change those settings.

```json
{
  "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. Turn Zero then publishes the debug build's signing identity alongside the store build's identity for production sign-in.

`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](/cloud/guides/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](/cloud/getting-started/deploy-an-application/#the-deploy-in-one-pass) shows, and again after each change. Before a deploy to production, make the compatibility check in [step 8](#8-read-the-versions-in-use-before-a-release). Once development is on, deploy to development and promote to production, as [Test in development, then promote](/cloud/guides/turn-on-development-and-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](/cloud/guides/sign-in-from-a-native-app/#2-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](/cloud/guides/sign-in-from-a-native-app/#10-sign-in-with-apple-s-or-google-s-own-sdk) 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/guides/manage-end-users/#2-list-invitations-and-users).

Cloud hosts the sign-in pages, issues session tokens, and runs the account realm's endpoints. When your backend runs on your computer, use the Account client to verify sessions through Cloud's verification route. The client can verify a token inside a hosted backend when it has the configured realm keys and the router's `x-turnzero-cloud-session` verdict. See [The router's session header](/cloud/concepts/verifying-an-end-user/#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](/cloud/guides/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. The backend checks which user sent it as [Tell which user sent a request](/cloud/guides/add-sign-in-to-your-app/#3-tell-which-user-sent-a-request) shows. In a hosted app, the router refuses a presented bearer that is expired or ended before the request reaches the backend. The sample's public route still needs its own 401 check for a request without a bearer. Keep that check in hosted and local runs, and in offline tests. See [Sign in from a native app](/cloud/guides/sign-in-from-a-native-app/#public-or-workforce-for-a-backend-that-verifies-the-bearer).

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 handle HTTP 426 by telling the user to update the app. Include the link when the response gives an `update_url`. If it is `null`, show the instruction without a link. Do not retry the request. See [Keep installed clients compatible](/cloud/guides/keep-installed-clients-compatible/).

A debug build sends the same header with its declared `client_id` and its own version. The realm includes that version in `versions_seen` and applies the client's `minimum_version`, as it does for a store build.

### 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](/cloud/guides/sign-in-from-a-native-app/#1-declare-the-client-on-each-environment-s-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](/cloud/guides/keep-installed-clients-compatible/#3-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

To send notifications, add `{"kind": "push"}` to the manifest's `services`. Store each provider credential for the application and environment. If the manifest names the providers, submit it to configure them. Otherwise use `configure_push` for the environment. Register each device after sign-in, as [Send push notifications](/cloud/guides/send-push-notifications/) describes. Sign in on a device running the app, register it with the environment you are testing, and send a notification to that device. Check that the installed app receives and shows it. The provider's acceptance alone cannot confirm what the device received.

### 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](/cloud/guides/sign-in-from-a-native-app/#public-or-workforce-for-a-backend-that-verifies-the-bearer) 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 six parts.

Give your AI coding agent these steps for a native app that signs in one company's staff. Use your own identifiers. Keep any file with the client secret outside the project.

1. Create the backend with `create_application` and keep the returned identifier. In the [manifest](#declare-the-backend-and-work-account-sign-in), declare `accounts` in `services` and set `audience.kind` to `workforce` with the company's `tenant`. Set `realm.sign_in_methods` to `["entra"]`. In `realm.entra`, use the same `tenant`, the app registration's `client_id`, and `client_secret_name` set to `entra-client-secret`.
2. Before submitting the manifest, call `store_secret` with the application identifier, target environment, and `name: "entra-client-secret"`. If the person deliberately shared the secret in this conversation, pass it as `value` and omit `value_file`. If the person supplied the secret in a file, pass its path as `value_file`, omit `value`, and run the returned command. [Store the client secret](#store-the-client-secret) explains when to repeat this for development or resubmit the manifest.
3. [Declare the native clients](#declare-native-clients-and-register-the-callback) under `realm.clients.production` or `realm.clients.development`. Set each build's `client_id` and `redirect_uris`. Submit the whole manifest with `submit_manifest`. Copy `realm.entra_callback` exactly into the Entra registration as a web redirect URI. Add `email` and `xms_edov` as optional ID token claims.
4. Read the callback and clients with `read_app_sign_in`, then check the secret's name with `list_secrets` in the same environment. Use the [native sign-in module](/cloud/guides/sign-in-from-a-native-app/#2-add-the-sign-in-module) with that environment's hostname, client ID and redirect URI. Send its access token to the backend as `Authorization: Bearer <token>`.
5. On the backend, use the [email verifier](#read-the-work-account-address). Take the Account package with `read_library` before importing it. Build its verification client without realm keys so it returns addresses. Read the bearer from the request and call `verifySession`. Return the verified address whose `source` is `tenant`, or `email: null` for a live session without one. Return 401 for a missing or refused session.
6. [Deploy the backend](#submit-and-deploy-the-backend) and ask someone in the tenant to sign in from a development build. Confirm `/me` returns that person's user ID and verified work email. Use the [signed-in route checks](#test-the-signed-in-route) to test missing and refused sessions as well.

#### 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.

```json
{
  "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" }
  }
}
```

A serverless application accepts this manifest with or without `health` and runs no health check. For a server, 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](/cloud/guides/author-the-manifest/#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](/cloud/guides/supply-a-secret-value-without-exposing-it/#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.

```json
{
  "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](/cloud/guides/sign-in-from-a-native-app/#1-declare-the-client-on-each-environment-s-realm) 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](/cloud/guides/keep-installed-clients-compatible/#3-raise-the-minimum-version) for when the app shows the update screen and how to choose store links.

#### Read the work-account address

For the server example below, use the Account package with `server.mjs` by default. Choose `server-fetch.mjs` when your server needs to stay package-free. An empty `packages` list in a starter manifest leaves that choice open.

Before importing `@turnzero/account`, call `read_library` with `entry: "account"` and follow [Use the feature package library](/cloud/guides/use-the-library/#3-add-an-entry-to-the-library-folder) to run its returned take line at the backend 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](/cloud/backend-packages/account/#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](/cloud/guides/add-work-account-or-apple-sign-in/#2-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.

The package-free version is a full alternative for this route, using the same verification route and the same user and address rules. It checks each session token with the platform without caching; the Account package adds verdict caching and a test double.

The verification request goes to the platform origin in `TURNZERO_CLOUD_API`, which needs no entry in `egress`. The manifests above therefore leave that list empty. For other outgoing calls, follow [Writing the egress list](/cloud/guides/author-the-manifest/#writing-the-egress-list).

Both versions here return only a verified tenant address; the [general sign-in example](/cloud/guides/add-sign-in-to-your-app/#without-the-account-package) accepts any verified address.

```js
// 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](/cloud/concepts/the-settings-a-deployed-copy-receives/) or a [provisioned local run](/cloud/guides/run-your-application-on-your-machine/#1-write-the-environment-file), with `TURNZERO_CLOUD_API` set; the offline test imports `me.mjs` without `server.mjs` and needs no such setting.

```js
// 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](/cloud/backend-packages/account/#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.

```js
// 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](/cloud/guides/sign-in-from-a-native-app/#2-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)](#6-call-the-backend-with-the-bearer) describes.

#### Use the route as a function

For a serverless application, use the package-free function below. Save the `me.mjs` helper above as `lib/me.mjs` and this file as `functions/me.js`. It answers `/me` with the same user and address rules as `server-fetch.mjs`.

For users who sign in with the emailed code, change the helper's address lookup to `const address = verdict.user.addresses.find((entry) => entry.verified);`. That accepts any verified address, as the [general sign-in example](/cloud/guides/add-sign-in-to-your-app/#without-the-account-package) does. Keep `functions/me.js` as written.

Deployed functions receive `TURNZERO_CLOUD_API` and `TURNZERO_CLOUD_APP_TOKEN` through `process.env` ([Read a function's settings](/cloud/guides/deploy-functions/#read-a-function-s-settings)). Keep the credential secret. The verification call goes to the platform directly, so the manifest needs no `egress` entry for it.

```js
// functions/me.js
import { me } from '../lib/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}`);
  },
};

const json = (status, body) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });

export default {
  async fetch(request) {
    try {
      const { status, ...body } = await me(request.headers.get('authorization'), accounts);
      return json(status, body);
    } catch (error) {
      console.error(error);
      return json(503, { error: 'verification_unavailable' });
    }
  },
};
```

The function starts no listening server and has no health route. A serverless deploy runs no health check, so the manifest's `/health` is unused. Read a failed verification call's console output with `read_logs`, using `source: "pool"`.

#### 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)](#4-sign-in-from-a-development-build) describes. You can also sign a [test end user](/cloud/guides/test-sign-in-with-test-end-users/) in using your AI assistant'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](/cloud/guides/test-sign-in-with-test-end-users/#7-test-a-local-run).

A job with only a [minted token](/cloud/concepts/glossary/#minted-token) and no `test_end_users` grant can test only requests with no session ([Choose the environment](/cloud/guides/test-sign-in-with-test-end-users/#1-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](/cloud/guides/sign-in-from-a-native-app/#public-or-workforce-for-a-backend-that-verifies-the-bearer)).

If the job's token has [the grant](/cloud/guides/mint-a-token/#a-token-for-test-end-users), call `request_route` with `test_end_user`, `environment` set to the environment you want to test, 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.

Without the Account package, test `me` offline by passing an object whose `verifySession` returns the verdict under test. Check the returned user and address for a live session, and 401 for a missing or refused session. [Test the server offline](/cloud/guides/add-sign-in-to-your-app/#test-the-server-offline) shows a local stand-in for the verification route itself.

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](/cloud/backend-packages/account/#test-with-the-double)).

Save the following test as `me.test.mjs`, beside `me.mjs`.

```js
// 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 assistant:** 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](/cloud/reference/refusals/) 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 assistant:** 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 uses (the `-dev` hostname for development) and look for the `client_id` in its clients. Add it to that environment's list in the manifest's `realm.clients` and call `submit_manifest`, or use `configure_app_sign_in` where the manifest lists no clients for that environment. Use `production` for a one-environment app. A `development` list is checked at submission and takes effect when `create_environment` adds development. |
| `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. Declare the URI in one of the supported forms and send it exactly as declared. Only the port may differ for a declared loopback 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 if supplied. Otherwise use the app's normal update channel. If the setting seems wrong, ask the app owner to verify it before changing the minimum. |

## Related

[From a server route to a function](/cloud/guides/deploy-functions/#from-a-server-route-to-a-function) explains what else changes when a server sample becomes a function.

- [Sign in from a native app](/cloud/guides/sign-in-from-a-native-app/) details every sign-in request, the refresh, the sessions list, and deletion.
- [Keep installed clients compatible](/cloud/guides/keep-installed-clients-compatible/) covers the version header, the minimum, and the versions in use.
- [Send push notifications](/cloud/guides/send-push-notifications/) covers the provider credentials, the device registration, and the send.
- [Deploy from your computer](/cloud/getting-started/deploy-an-application/) covers the artifact, the deploy, and the promote.
- [Manage end users](/cloud/guides/manage-end-users/) lists every realm setting.
