---
title: Serve a web client
description: Ship a web page's files with your backend, served at your app's address ahead of your routes, or build pages and forms on your own routes.
slug: /guides/serve-a-web-client
order: 4
visibility: public
redirects_from: []
---

# Serve a web client

Prompt:

> Add a simple web page to this backend so people can use it in a browser.

Also works:

- "Use KaTeX to render math on the page, without a CDN."
- "Serve the front end from the same app."
- "Add a favicon and the app's logo to the page."

A web client is the set of files a browser loads: the page, its scripts and styles, fonts, and images. Put the client's built files under `client/`, beside `package.json`, and deploy. Every file there is public ([step 1](#1-put-the-client-s-built-files-under-client-every-one-public)). The platform responds to a `GET` for each file at `/` followed by its name, before your routes see the request ([step 2](#2-know-what-the-platform-serves-and-what-reaches-your-routes)).

For a site of HTML, CSS and images, follow [Publish a static site](/cloud/guides/publish-a-static-site/) to publish the files as a serverless application.

For a new app, `turnzero scaffold --template notes-app` writes a web app with sign-in and private notes in a database. Use `--template ai-chat` for sign-in and an AI conversation held in the page. Both include the page's three starting files, its shell ([The notes-app template](/cloud/concepts/turnzero-command/#the-notes-app-template); [The ai-chat template](/cloud/concepts/turnzero-command/#the-ai-chat-template)).

Without a shell, adapt the [notes-app example files](/cloud/examples/notes-app/) or the [ai-chat example files](/cloud/examples/ai-chat/) and follow [Deploy from a chat](/cloud/getting-started/build-an-app-from-a-chat/).

## What your AI tool does

- Reads the `skill:deploy` [skill](/cloud/concepts/glossary/#skill) (`read_context`, id `skill:deploy`) and follows its `web-client` item, which says where the files go.
- Builds the client and puts its files under `client/`. That includes the files of each third-party library the page uses, copied from the installed package.
- For a page your server builds, writes its route, the form post, and the redirect after the post, as step 7 shows.
- Deploys as [Deploy from your computer](/cloud/getting-started/deploy-an-application/) describes. Then it reads the deploy's `client_notice`, which lists the files the platform will serve.
- Requests the page, a font, and a script on the environment's hostname to check them.
- Asks you what the page should show before it writes the client. Before it deploys, it also asks you about any file under `client/` that should stay private, since every file there is public. No step needs your approval in a browser.

## What you need

- What the page should do, or a built web client.

## Before your AI starts

**For the AI tool:** Check the following before starting.

- A connected, signed-in AI tool ([Connect your AI assistant](/cloud/getting-started/connect-your-tool/)).
- A backend that deploys, and the folder the turnzero command zips: the one that contains `package.json` and its lockfile.
- Each third-party library the page uses, such as KaTeX, installed as a development dependency. Its files can then be copied into `client/`, and the platform's install skips it.

## Steps

### 1. Put the client's built files under client/, every one public

A web client is every file under the zip's `client/` folder. Your AI tool writes the built files there, beside `package.json`, before the deploy. Three of them are the page's shell: `client/index.html`, `client/app.js`, and `client/styles.css`.

Every file under `client/` is public. Anyone who can open the page can request any of them, so keep private files out of the folder. Where the manifest's [audience](/cloud/concepts/glossary/#audience), the setting for who may use the app, is `invited` or `workforce`, a visitor must sign in first (step 5).

This folder holds the shell, a favicon, and KaTeX's script, stylesheet, and fonts:

```text
package.json
src/main.mjs
client/index.html
client/app.js
client/styles.css
client/favicon.ico
client/vendor/katex/katex.min.js
client/vendor/katex/katex.min.css
client/vendor/katex/fonts/KaTeX_Main-Regular.woff2
```

Your AI tool copies a library's files from the installed package, here on macOS or Linux:

```sh
mkdir -p client/vendor/katex
cp node_modules/katex/dist/katex.min.js node_modules/katex/dist/katex.min.css client/vendor/katex/
cp -R node_modules/katex/dist/fonts client/vendor/katex/
```

Each file is served at `/` followed by its name below `client/`. The page loads every file from the application's own address, so no third-party server sees your visitors. KaTeX's stylesheet names its fonts relative to itself, so they load from `/vendor/katex/fonts/`. A relative link between files under `client/` resolves as it does in the folder: from `client/notes/first.html`, `../styles.css` loads `/styles.css`. A page your server returns at its own path, such as `/notes/7` (step 2), resolves relative links against that path, so give its links full paths, such as `/styles.css`.

```html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Notes</title>
  <link rel="icon" href="/favicon.ico">
  <link rel="stylesheet" href="/styles.css">
  <link rel="stylesheet" href="/vendor/katex/katex.min.css">
  <script defer src="/vendor/katex/katex.min.js"></script>
</head>
<body>
  <h1>Notes</h1>
  <ul id="notes"></ul>
  <script src="/app.js"></script>
</body>
</html>
```

The script calls the backend on the same address. So the browser sends the user's sign-in cookie with each request, and you need no cross-origin (CORS) setting. This script reads `GET /notes`, the route that [Build a database-backed service](/cloud/getting-started/build-a-database-backed-service/) adds.

```js
// client/app.js
fetch('/notes')
  .then((response) => response.json())
  .then((notes) => {
    const list = document.getElementById('notes');
    for (const note of notes) {
      const item = document.createElement('li');
      item.textContent = note.title;
      list.append(item);
    }
  });
```

A web client is optional. An application without one, such as the backend of a mobile app, ships no `client/` folder, and every request reaches its own routes. [Build a mobile app's backend](/cloud/getting-started/build-a-mobile-app-backend/) walks through that shape.

### 2. Know what the platform serves and what reaches your routes

The [serving router](/cloud/concepts/glossary/#serving-router) responds to a `GET` for a client file itself, ahead of your routes. A request for a page, script, font or image has no per-request charge and never wakes your application. A `GET` of `/` or `/index.html` returns `client/index.html`, and `/app.js` and `/styles.css` return the shell's script and stylesheet.

These requests reach your application instead:

- every `HEAD` and `POST`, and every other method, even on a client file's path;
- a path that names no client file, such as `/notes` or a single-page application's own route `/notes/7`;
- a path holding `%`, since the router matches the path exactly as the browser sends it and never decodes it;
- a request the platform's file store does not respond to in time, as step 5 explains. The file store is where the deploy keeps your client files.

Your own static serving of `client/`, such as `express.static`, is redundant on a deployed copy: only the requests above reach it. With `turnzero` 0.35.0 or later and a numeric port, the command also serves client files locally. Other local runs need your server to serve them (step 6).

If a page should load at a path of its own, such as `/notes/7`, your server must return `client/index.html` for that path itself. For a server application, the router has no fallback page and returns no folder's index file.

### 3. Keep names and sizes within the limits

The deploy checks each file name below `client/` before it writes anything. A file is served only if each part of its name between slashes uses ASCII letters, digits, `-`, `_`, `.`, and `~` alone. No part may start or end with a dot.

A name may hold up to 32 parts and 512 characters. Its first part may not be `__account` or `__router`, the platform's own folders, in any letter case. The deploy skips any other name, such as `.DS_Store`, `.env`, a name with a space, or a name with an accented letter. The platform never serves a skipped file.

A version's client files have limits. A zip past any limit is refused 400 `artifact_layout_invalid` before a version is added, and the refusal names the limit:

| Limit | Value |
| --- | --- |
| Files served | 2,000 |
| One file | 25 MiB |
| All files together | 50 MiB |

Keep long audio or video in a [storage area](/cloud/guides/store-files/) instead. A browser fetches it from there through a download grant.

If `client/` holds a file beyond the shell, or a name the deploy skipped, the deploy's response includes `client_notice`. It counts the files the router will serve, names up to twenty beyond the shell, and names up to twenty skipped files, then counts the rest. It is a notice only and refuses nothing. Your AI tool reads it after each deploy. A file your backend once served only after a check of its own is public from that deploy on.

### 4. Know the headers, the revalidation, and the compressed forms

On a deployed copy, each client file is returned with these headers:

- The file's type, `Content-Type`, from the platform's table of file extensions, such as `text/javascript` for `.js` and `.mjs`, `font/woff2` for `.woff2`, and `image/webp` for `.webp`. A text or JSON type carries `; charset=utf-8`. An extension the table does not name gets `application/octet-stream`.
- The header `X-Content-Type-Options: nosniff`, so a browser uses that type and never guesses another.
- The header `Cache-Control: no-cache`, so a browser asks again before it reuses a file, and a deploy's new files reach it at once.
- The file's tag, `ETag`, which is the file's SHA-256 hash in quotes.

A browser that asks again sends that tag in its `If-None-Match` header. If the file has not changed, the router returns 304 with no body, so the file is not sent again. An unchanged file keeps its tag across deploys, so a returning visitor downloads only what changed.

The deploy also writes a compressed (gzip) copy of some files. It writes one for each `.html`, `.css`, `.js`, `.mjs`, `.json`, `.map`, `.svg`, `.txt`, `.xml`, `.webmanifest`, and `.wasm` file of at least 1 KiB, where gzip makes it a tenth smaller or more. A request whose `Accept-Encoding` header accepts gzip receives that copy. The response then carries `Content-Encoding: gzip`, a tag of its own, and `Vary: Accept-Encoding`.

The platform sets no content security policy on a client file. If the page needs one, set it in `client/index.html`.

### 5. Know what a client file counts, and who may read it

A client file beyond the shell counts its bytes as `data_transfer_bytes`, charged from the account's balance at the `data-transfer` rate. The balance read's `lines` name that charge. It counts no backend action and nothing toward the [per-address limits](/cloud/concepts/egress-firewall-and-request-limits/). A 304 counts nothing. The shell's three files count nothing at all.

When the account has used its balance, every application pauses until the next UTC month starts ([Size and usage](/cloud/guides/plan-and-usage/)). Every request on either hostname is refused 429 `account_paused`, including the shell files and realm paths. A browser asking for HTML gets the platform's pause page; any other caller gets the JSON refusal. Each carries `Retry-After`.

If the platform's file store does not respond, the router holds that failure for 30 seconds. In that time, a request for a file beyond the shell reaches your application as an ordinary request. It counts toward the per-address limits.

Under an `invited` or `workforce` audience, every client file needs a signed-in visitor, including the page's shell. A browser that is not signed in goes to the sign-in page first. The exception is a path the audience lists in `session_free_paths` ([The manifest](/cloud/concepts/the-manifest/#the-audience-kinds)).

### 6. Serve the files yourself in a local run

With `turnzero` 0.35.0 or later, start `turnzero run --port 3000` in the application's folder. Where it holds `client/`, the command serves each client file at its own path, ahead of your routes. It gives your application a free port as `PORT`. Open the command's printed address.

Files are read on each request, so an edit appears on the next load. Names match in their letter case on every disk. A name the deploy's zip leaves out, or a path containing a link, falls through to your application. `.deployignore` is not read, so a file it hides can still be served locally.

Local responses use the same content type, `nosniff`, and `no-cache` headers, but no `ETag` or gzip copy. If a file cannot be read, the command responds with 502 instead of passing the request to your app.

Without `--sign-in`, the listener binds on all network interfaces. An application that binds only to loopback can therefore be reached through it from elsewhere. With `--sign-in`, it binds only to loopback; [Test a local run](/cloud/guides/test-sign-in-with-test-end-users/#7-test-a-local-run) describes browser sign-in.

For an older command, no numeric port, or starting Node.js directly, keep static serving in your own server. The sample below serves `client/` while `APP_ENVIRONMENT` is `local`. On the platform it returns `false`, since the router responds first. While the file store fails (step 5), your own routes respond instead.

A test runs this sample over a client folder and checks a served file, a skipped name, and a path outside the folder.

```js
// src/client_files_local.mjs: a local run alone.
import { readFile } from 'node:fs/promises';
import { extname } from 'node:path';

const folder = new URL('../client/', import.meta.url);
const types = {
  '.html': 'text/html; charset=utf-8',
  '.js': 'text/javascript; charset=utf-8',
  '.mjs': 'text/javascript; charset=utf-8',
  '.css': 'text/css; charset=utf-8',
  '.json': 'application/json; charset=utf-8',
  '.svg': 'image/svg+xml',
  '.png': 'image/png',
  '.ico': 'image/x-icon',
  '.woff2': 'font/woff2',
};
const part = /^[A-Za-z0-9_~-]([A-Za-z0-9._~-]*[A-Za-z0-9_~-])?$/;
const reserved = ['__account', '__router'];

export async function serveClientFile(req, res) {
  if (process.env.APP_ENVIRONMENT !== 'local' || req.method !== 'GET') return false;
  let path;
  try {
    path = new URL(req.url, 'http://localhost').pathname;
  } catch {
    return false;
  }
  const name = path === '/' ? 'index.html' : path.slice(1);
  const segments = name.split('/');
  if (name.length > 512 || segments.length > 32) return false;
  if (reserved.includes(segments[0].toLowerCase())) return false;
  if (!segments.every((segment) => part.test(segment))) return false;
  try {
    const body = await readFile(new URL(name, folder));
    res.writeHead(200, { 'content-type': types[extname(name).toLowerCase()] ?? 'application/octet-stream' });
    res.end(body);
    return true;
  } catch {
    return false;
  }
}
```

Your server calls it first, as the router would, and goes on to its own routes when it returns `false`:

```js
// src/main.mjs
import { createServer } from 'node:http';
import { serveClientFile } from './client_files_local.mjs';

createServer(async (req, res) => {
  if (await serveClientFile(req, res)) return;
  // Your routes, the health path among them.
  res.writeHead(404).end();
}).listen(process.env.PORT);
```

A name the deploy would skip is never served by these lines either.

### 7. Serve a page from your own routes, and take a form post

Your server can build a page itself, on a route of its own, with no file under `client/`. The router passes your response's status, `Content-Type`, and body to the browser unchanged. So a route can return `text/html` as well as JSON.

Give such a page a path that names no client file. A `GET` for a client file's path is served from `client/` and does not reach your server (step 2). Where the application ships `client/index.html`, `/` is that file, so a page your server builds needs another path, such as `/guestbook`.

A form with `method="post"` sends its fields in the body as `application/x-www-form-urlencoded`. The post reaches your server, since only a `GET` is served from `client/`. The router forwards a body up to its [request size limit](/cloud/concepts/egress-firewall-and-request-limits/#the-request-size-limit) and refuses a larger one 413 `request_too_large`. Your server reads the body and parses it with `URLSearchParams`. Set a smaller limit of your own, since a form's fields are short.

Each page request and each post reaches your application. Each is subject to the [per-address limits](/cloud/concepts/egress-firewall-and-request-limits/#the-per-address-and-per-user-limits).

After a post, respond `303` with a `Location` header. The browser then requests that address with `GET`, so a reload of the page does not send the form again. The router passes the `Location` header to the browser unchanged and does not follow it.

A relative `Location`, such as `/guestbook`, is enough for a page on the same hostname. The browser resolves it against the address it posted to. So the same redirect works on the production hostname, on the development hostname, on your own domain, and in a local run.

Build an absolute address from `APP_PUBLIC_HOST` where the address leaves the page, such as a link in an email or a return address you give another service. `APP_PUBLIC_HOST` holds the hostname without `https://`, so the address is `https://` followed by it. In a deployed copy, never build one from the request's `Host` header, which names the platform's internal address for the environment ([What the router sets on each request](/cloud/backend-packages/nodejs-runtime/#what-the-router-sets-on-each-request)).

The router passes the request's `Cookie` header to your server and your `Set-Cookie` headers to the browser. It removes any `Domain` attribute, so each cookie belongs to the hostname that set it alone.

Under an `invited` or `workforce` audience, a post without a signed-in session is refused 401 `authentication_required` before it reaches your server, unless its path is under a session-free prefix your manifest lists ([The manifest](/cloud/concepts/the-manifest/#the-audience-kinds)). Outside such a prefix, a page request without one goes to the sign-in page first.

Escape every value a visitor sent before you write it into the page, as the sample's `escape` does. The text then shows as text and never runs as HTML.

This server builds a guestbook page at `/guestbook` and takes its form post there. It keeps the entries in memory to stay short. A running copy's memory empties when the copy stops or restarts, and each copy has its own. So keep real entries in a [database](/cloud/getting-started/build-a-database-backed-service/). Its health path is `/health`. A test runs this sample as a server and checks the page, a form post and its redirect, an escaped entry, and a body past its limit.

```js
// src/guestbook.mjs: a page the server builds at /guestbook, and the form that posts to it.
import { createServer } from 'node:http';

const FORM_LIMIT = 16 * 1024; // A form's fields are short: read far less than the router forwards.
const entries = []; // In memory to keep the sample short.

const escape = (text) => text.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);

const page = () => `<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Guestbook</title></head>
<body>
  <h1>Guestbook</h1>
  <form method="post" action="/guestbook">
    <input name="note" maxlength="200" required>
    <button>Sign</button>
  </form>
  <ul>${entries.map((entry) => `<li>${escape(entry)}</li>`).join('')}</ul>
</body>
</html>`;

// The posted fields, or null for a body past FORM_LIMIT. The whole body is read either way.
async function readForm(req) {
  const chunks = [];
  let size = 0;
  for await (const chunk of req) {
    size += chunk.length;
    if (size <= FORM_LIMIT) chunks.push(chunk);
  }
  return size > FORM_LIMIT ? null : new URLSearchParams(Buffer.concat(chunks).toString('utf8'));
}

const port = Number(process.env.PORT ?? 8080);
createServer(async (req, res) => {
  // A target that does not parse as a URL names no route, so it gets a 404 below.
  let pathname = null;
  try {
    pathname = new URL(req.url, 'http://localhost').pathname;
  } catch {}
  if (req.method === 'GET' && pathname === '/health') return res.writeHead(200).end('ok');
  if (pathname !== '/guestbook') return res.writeHead(404).end();
  if (req.method === 'GET') return res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }).end(page());
  if (req.method !== 'POST') return res.writeHead(405, { allow: 'GET, POST' }).end();
  if (!String(req.headers['content-type']).startsWith('application/x-www-form-urlencoded')) return res.writeHead(415).end();
  const form = await readForm(req);
  if (form === null) return res.writeHead(413).end();
  const note = form.get('note')?.trim().slice(0, 200);
  if (note) entries.push(note);
  // 303: the browser requests /guestbook with GET, on the hostname it posted to.
  res.writeHead(303, { location: '/guestbook' }).end();
}).listen(port, () => console.log(`listening on ${port}`));
```

### 8. Deploy and check the page, a font, and a script

Your AI tool deploys the application as [Deploy from your computer](/cloud/getting-started/deploy-an-application/) describes, and reads `client_notice` in the response. Binary assets can go inline as base64, up to 512 KiB each, or as `stored` entries without that per-file cap. With no shell, ask your user to [upload assets you cannot read](/cloud/guides/store-files/#upload-a-file-from-the-application-s-page), then use stored entries.

The 4 MiB total and 200-entry limits still apply. Beyond them, use `turnzero deploy`; with no shell, ask your user to deploy from a computer with a shell. Once the deploy ends in the state `deployed`, your AI tool requests three files on the environment's hostname with `GET`:

```sh
curl -s -D - -o /dev/null https://<hostname>/
curl -s -D - -o /dev/null https://<hostname>/vendor/katex/fonts/KaTeX_Main-Regular.woff2
curl -s -D - -o /dev/null -H 'Accept-Encoding: gzip' https://<hostname>/vendor/katex/katex.min.js
```

Each response is 200, with the file's type, `nosniff`, and an `ETag`, and the script's response is in gzip. Check with `GET`, never with `curl -I`, which sends `HEAD`, and `HEAD` reaches your application. Under an `invited` or `workforce` audience, check in a signed-in browser instead.

## Expected result

A request for `/` returns the page, and every file under `client/` that the deploy accepted returns at its own path, with its type, its tag, and a gzip form where one was written. Every other request reaches your application's routes. A page your server builds comes from its own route, and its form post ends in a `303` to a path on the same hostname. A file beyond the shell counts toward data transfer and never toward backend actions, except while the file store fails (step 5).

## Refusals

See the [refusals reference](/cloud/reference/refusals/) for other platform errors.

The deploy's own refusals are in [Deploy from your computer](/cloud/getting-started/deploy-an-application/#refusals).

| Refusal | Status | Cause | Remedy |
| --- | --- | --- | --- |
| `artifact_layout_invalid` | 400 | The zip's client files pass a bound: more than 2,000 files, one file over 25 MiB, or more than 50 MiB together. The `detail` names the bound. | Ship fewer or smaller client files, keep long media in a storage area, and deploy again (step 3). |
| `not_deployed` | 404 | The environment has no deployed version yet, so there is no page to serve. | Deploy to the environment, then request the page again. For production on an application with two environments, promote a version instead. |
| `account_paused` | 429 | The account has used its balance. Every request is refused, including all client files and realm paths. A browser asking for HTML gets the pause page; other callers get JSON. Each response carries `Retry-After`. | Wait until the next UTC month starts. |

## Related

- [Deploy from your computer](/cloud/getting-started/deploy-an-application/) builds the zip, uploads it, and deploys it.
- [What the deploy zip holds](/cloud/concepts/what-the-deploy-zip-holds/) gives the zip's limits and the deploy's notices.
- [Store files](/cloud/guides/store-files/) keeps files your users upload, and long audio or video, which the page fetches through a download grant.
- [Size and usage](/cloud/guides/plan-and-usage/) reads the data transfer your client files count.
- [Add sign-in to your app](/cloud/guides/add-sign-in-to-your-app/) lets the page's users sign in.
- [Build a mobile app's backend](/cloud/getting-started/build-a-mobile-app-backend/) covers an application with no web client.
- The turnzero command's [notes-app template](/cloud/concepts/turnzero-command/#the-notes-app-template) and [ai-chat template](/cloud/concepts/turnzero-command/#the-ai-chat-template) write the three shell files in `client/`, with sign-in and either private database records or an AI conversation.
