Serve a web client #

View this page as Markdown

On this page

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 files visitors may load under client/, beside package.json (step 1). The router serves an admitted GET for a matching file before your routes see it (step 2).

For a site of HTML, CSS and images, follow Publish a static site to publish the files as a serverless application.

For a new app with sign-in and private notes in a database, start with functions-sign-in if it can run as functions. Use server-sign-in when the app needs a server. Use server-ai-chat for sign-in and an AI conversation. Each template includes the starting HTML, CSS, and JavaScript in client/.

Without a shell, use the functions-sign-in example, the server-sign-in example, or the server-ai-chat example. Follow the example's From a chat section and Deploy from a chat.

What your AI does #

  • Reads the skill:deploy 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 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 deploying, it checks whether any file under client/ needs its own access check. 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 assistant: Check the following before starting.

  • A connected, signed-in AI assistant (Connect your AI assistant).
  • 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 files visitors may load under client/ #

A web client is every file under the zip's client/ folder. Your AI assistant 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.

Use client/ for browser assets. Under a public audience, anyone can fetch every file under client/ without signing in. Under an invited or workforce audience, every signed-in user of the app can fetch every file there, and anyone can fetch a file on a path the manifest lists in session_free_paths. The router makes no per-user check on these files. For a private file that needs its own access check, keep it outside client/ and serve it through your application.

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

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 assistant copies a library's files from the installed package, here on macOS or Linux:

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.

<!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 adds.

// 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. Requests that the platform handles itself, such as a matching manifest redirect, stop at the router. The remaining requests reach the application's own routes. Build a mobile app's backend walks through that shape.

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

The serving router checks for a matching manifest redirect before it serves a client file or calls your application. A GET for a client file has no per-request charge and never wakes your application. That applies when the router serves the file. If the file store fails on a server app, the request can reach and wake the app. With no matching rule, a GET of / or /index.html returns client/index.html, and /app.js and /styles.css return the shell's script and stylesheet.

On a server application, when no manifest redirect matches the request, these requests reach your application:

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

For a serverless version with no matching manifest redirect, the router responds to both GET and HEAD for client files. If no client file matches, requests at or beneath a function's path go to that function on any method. See Publish a static site for page and 404 handling, and Deploy functions for function paths.

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 provides no fallback page and does not automatically serve a folder's index.html.

3. Keep names and sizes within the limits #

The deploy checks each file name below client/ before it writes anything. Each part of a file name between slashes may use only ASCII letters, digits, and the characters -, _, ., ~, and @. No part may start or end with a dot. A name such as logo@2x.png is allowed.

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 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 assistant reads it after each deploy. To keep a backend route's per-file access check, leave its files outside client/.

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.
  • Cache-Control: no-cache by default. The browser asks again before reusing the file.
  • The file's tag, ETag, contains the SHA-256 hash of the bytes the router sends, in quotes.

The router serves matching client files before it calls your application. For a custom header, use an application route with no matching file in client/. Use a manifest rule for a redirect from one exact path to another on the same hostname. For redirects that match a pattern or go to another hostname, use an application route with no matching file in client/.

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 served form keeps its tag across deploys. A browser that sends that form's tag can reuse its copy after a 304 response.

The deploy writes a gzip copy for eligible files of at least 1 KiB when gzip makes them a tenth smaller or more. Eligible extensions are .html, .css, .js, .mjs, .json, .map, .svg, .txt, .md, .xml, .webmanifest, and .wasm.

If a copy exists and the request’s Accept-Encoding header accepts gzip, the router serves it with Content-Encoding: gzip and its own tag. When a file has a gzip copy, either form includes Vary: Accept-Encoding.

Your server handles compression for the responses it returns. The router passes the browser's Accept-Encoding header to your server.

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

Cache one public folder for a year #

In the manifest, set immutable_client_folder to one folder below client/, such as assets or static/build. Give its path without a slash at either end. Use a path that the client-file rules above would allow for a file inside the folder. The first segment cannot be __account or __router, regardless of case.

check_manifest and submit_manifest return manifest_invalid at this member for an invalid path or an invited or workforce audience.

With a public audience, files served from that folder carry Cache-Control: public, max-age=31536000, immutable. Files outside the folder, files named index.html at any depth, and responses that set a session cookie keep no-cache. After you restrict the audience to invited or workforce, all client file responses use no-cache. This applies even if the serving version was published while the audience was public.

The next deploy records the folder with the version it publishes. A promote carries the folder recorded with that version. A rollback to a version published without the member uses no-cache.

Give each file a new name when its content changes. A bundler can add a content hash to each name. Keep page files outside this folder.

A browser can keep a copy for up to a year, even if you later restrict the audience. On a custom domain declared with proxied_by, your own proxy can also keep a copy for the year.

After deploying, request a published file other than index.html from the folder and a published file outside it. Confirm that both responses return HTTP 200. Check that Cache-Control is public, max-age=31536000, immutable for the file inside the folder and no-cache for the file outside it.

Redirect an exact path #

Add redirects to manifest.json when an old path should send visitors to a new one on the same hostname. A manifest can list up to 200 rules. Each rule has a from path, a to path and a status of 301 (permanent) or 302 (temporary). This example sends visitors from /old-pricing to /pricing.

{
  "redirects": [
    { "from": "/old-pricing", "to": "/pricing", "status": 301 }
  ]
}

Use paths up to 512 characters that start with /. After the initial slash, use ASCII letters, digits, -._~!$&'()*+,;=:@, /, or % followed by two hexadecimal digits. Leave out query strings, fragments, backslashes, . and .. segments, and escaped dots such as %2e or %2E.

Give every rule a different from. The router matches that path character for character, so /old, /old/ and /Old are three different paths. The platform reserves /__account/ and /__router/ paths as sources. Start to with a single slash. It may point to a platform page such as /__account/signin. Choose a destination that no rule uses as its from, including its own. On a static site, don't redirect a folder's path with its trailing slash to the same path without it, because the platform adds the slash back and creates a loop.

Run check_manifest, then submit_manifest once the manifest passes. Both refuse an invalid rule with 400 and manifest_invalid and name its field in the manifest. Deploy the version, then request /old-pricing?ref=email without following redirects. The response has status 301, Location: /pricing?ref=email and Cache-Control: no-cache. Check on the deployed hostname. turnzero run --origin https://dev.turnzero.ai skips manifest redirect rules.

A rule redirects a matching GET or HEAD before the router serves a client file, calls a function or sends the request to your server. Other methods and WebSocket upgrades follow their usual routes. The sign-in gate for an invited or workforce audience still runs first, except on paths listed in session_free_paths.

Keep redirect sources clear of health and smoke paths if visitors need those paths to reach the app. The deploy checks still reach the app directly. A new or changed rule starts serving in an environment when you deploy the version there. Each version keeps the rules it was deployed with. A promote or rollback serves the rules of the version it puts live.

A redirect response adds no data transfer, backend actions or use of the per-address request limit. If the application is over a traffic limit, the router returns 429 with usage_over_quota for the path, as it does for a client file.

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

When the router sends a client file, the bytes in the response body count as data transfer. Your account pays for them from its balance at the data-transfer rate. For a server app, the main page (client/index.html), script (client/app.js), and stylesheet (client/styles.css) are exempt. For a serverless app, those files count too. A file the router serves uses no backend actions and counts toward none of the limits per address. A 304 response sends no file bytes.

Every application pauses when the account uses its available balance. The pause ends when the account has Free Allowance available again or credit it can use (Size 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.

For a server application, if a read from the platform's file store fails, the router remembers that failed read 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. If the router cannot read the version's file index, it also skips manifest redirect rules during the hold. Those requests follow the server's usual routing. If the store cannot return a serverless version's file index or a listed file, the router returns 502 upstream_failed.

Under an invited or workforce audience, the router applies the sign-in check to client files, including the page's shell. The router sends a signed-out page visit to the sign-in page. Paths listed in session_free_paths can pass the audience check without a session (The manifest). The router serves an admitted file without calling the application's routes.

6. Serve the files yourself in a local run #

With turnzero 0.35.0 or later, start turnzero run --origin https://dev.turnzero.ai --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.

turnzero run --origin https://dev.turnzero.ai serves files locally with their content type, nosniff, and Cache-Control: no-cache, even when the manifest declares immutable_client_folder. It skips manifest redirect rules. Local responses omit ETag and gzip copies. 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 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 a deployed copy, this helper always returns false. If the router forwards a request during a file-store failure, your server handles it with its other routes. The sample returns 404.

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

// 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:

// 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);

This local example checks file names. Keep only files you intend to serve in that folder. The example follows symbolic links in the folder and serves their targets, even files outside the folder. It does not apply .deployignore.

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

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

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

// 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 assistant deploys the application as Deploy from your computer 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, then use stored entries.

The deploy_files route still has its 4 MiB total and 200-entry limits. Beyond them, use the command returned by tzcloud_deploy_command or the ZIP upload route in Ways to deploy. If your AI assistant has no shell, ask the person to deploy from a computer that supports the chosen route.

Once the deploy ends in the state deployed, request three files on the environment's hostname with GET:

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

Check for 200, the file's type, nosniff, and an ETag on each response. Expect Content-Encoding: gzip for the script if this version has a compressed copy.

Use GET on a path with no manifest redirect for these checks. On a server, curl -I sends HEAD to your application unless a manifest rule redirects it first. On a serverless version, the router responds to HEAD for a client file without calling a function. Under an invited or workforce audience, check in a signed-in browser instead.

Expected result #

An admitted request for / returns the page. Accepted files under client/ have their own paths, types, tags, and gzip copies where the deploy wrote them. Step 2 explains which requests reach the application. 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 for other platform errors.

The deploy's own refusals are in Deploy from your computer.

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 for Free Allowance to renew or for credit you can use.