> ## Documentation Index
> Fetch the complete documentation index at: https://developers.zite.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Zite.js for Start apps

> How Start app code works: server functions and how pages call them, where each piece of code runs, the installed libraries, the Worker runtime, environment variables, and links into the workspace.

A Start app is a standard TanStack Start app on React 19, with `zitejs` for access and data. Pages render on
the server first, then run in the browser. Server code lives in server functions, which pages call from their
loaders and event handlers, and every server function starts from a `zitejs` factory that decides who may
call it. This page covers what every app uses. The pages linked at the end cover the rest.

## The surface

Platform code comes through `zitejs/*` imports. `zitejs/db`, `zitejs/integrations`, and `zitejs/email` are
generated into your workspace, which is why they know your table and connection names.

| Import | What it gives you |
| - | - |
| `zitejs/start` | `signedInFn` and `publicFn` for [server functions](#server-functions), `ZiteError`, `loginHref`, `createZiteRouter`, `createAutomation`, and the `signedIn` and `anyone` access for [API routes](https://developers.zite.com/framework/api-routes.md) |
| [`zitejs/db`](https://developers.zite.com/framework/database) | The typed `zite` database client: table methods and read-only `zite.sql()` |
| [`zitejs/auth`](https://developers.zite.com/framework/access-and-sign-in) | `loginWithRedirect`, `logout`, and `updateProfile`, for pages |
| [`zitejs/auth/server`](https://developers.zite.com/framework/app-config#auth-hooks) | `ziteAuth`, for sign-in hooks in `zite.auth.ts` |
| [`zitejs/integrations`](https://developers.zite.com/framework/secrets-and-integrations) | `integrations.get('<name>')`: credentials for connected services |
| [`zitejs/email`](https://developers.zite.com/framework/email) | The `Email` client, once the app has an `email` settings entry |
| [`zitejs/meta`](#links-into-the-workspace) | `ZiteMeta.getWorkspace()`: links into the workspace |
| [`zitejs/schedules`](https://developers.zite.com/automations/schedules) | `ZiteSchedules`: schedules end users set at runtime |
| [`zitejs/upload`](https://developers.zite.com/framework/file-uploads) | `useUpload`, for uploading files from a page |
| [`zitejs/pdf`](https://developers.zite.com/recipes/generate-pdfs) | `ZitePdf`, which renders HTML to a PDF |

## Server functions

Every server function starts from a `zitejs` factory, which decides who may call it:

* `signedInFn`: only signed-in users, and `context.user` is a `User`.
* `publicFn`: anyone, signed in or not, and `context.user` is `User | null`. This is for external apps: an
  internal app signs everyone in first, so it uses `signedInFn` throughout, and the build refuses a
  `publicFn` there (`public-in-internal`).

The shape is:

```typescript theme={"system"}
export const name = signedInFn({ method, description })
  .validator(zodSchema)
  .handler(async ({ data, context }) => ...);
```

* `method` is `'GET'` for reads and `'POST'` for writes. `description` is one plain sentence, and the types
  require it. It labels the function in the app's **Logic** tab.
* `.validator(z.object({...}))` checks the input, which the handler gets as `data`. Callers pass `{ data }`
  even when every field is optional (`fn({ data: {} })`). Called with nothing, the validator gets `undefined`
  and the call fails with "Invalid input".
* Each server function is its own exported top-level `const`, with a name unique in the app, since the name
  is its id in the editor. TanStack Start compiles only a chain written out in that `const`: a server
  function returned from a helper or kept in an object fails when it's called.
* Raw `createServerFn` from TanStack, or a factory of your own built on it, fails the build
  (`raw-server-fn`): access has to come from `zitejs`.
* Pages read through a query's `queryFn` and write through a mutation's `mutationFn`, as in
  [Pages and loaders](#pages-and-loaders). A server function that nothing but other server functions calls
  fails the build, so shared logic goes in a `*.server.ts` helper that each handler calls.

Server code lives in two kinds of file:

* `*.functions.ts` (for example `src/lib/customers.functions.ts`) exports the server functions pages call.
* `*.server.ts` holds server-only helpers. Page code never imports one: the build refuses it.

```typescript theme={"system"}
// src/lib/requests.functions.ts
import { z } from 'zod';
import { signedInFn, ZiteError } from 'zitejs/start';
import { zite } from 'zitejs/db';
import { toView } from './requests.server';

export const listMyRequests = signedInFn({
  method: 'GET',
  description: 'Requests the signed-in user filed',
}).handler(async ({ context }) => {
  const { records } = await zite.requests.findAll({
    filters: { createdBy: context.user.id },
    limit: 100,
  });
  return records.map(toView);
});

export const closeRequest = signedInFn({
  method: 'POST',
  description: 'Resolves a request the signed-in user filed',
})
  .validator(z.object({ id: z.string() }))
  .handler(async ({ data, context }) => {
    const request = await zite.requests.findOne({ id: data.id });
    if (!request || ![request.createdBy ?? []].flat().includes(context.user.id)) {
      throw new ZiteError('NOT_FOUND', 'No such request');
    }
    await zite.requests.update({ id: request.id, record: { done: true } });
  });
```

```typescript theme={"system"}
// src/lib/requests.server.ts
export const toView = (request: { id: string; title?: string | null; done?: boolean | null }) => ({
  id: request.id,
  title: request.title ?? '',
  done: Boolean(request.done),
});
```

### Checking the caller

A server function is reachable without the page that calls it, so it checks what it returns and changes:

* `signedInFn` proves only that someone is signed in. A function that takes a record id loads that record
  and checks it belongs to `context.user` before returning or changing it, because the id came from the
  browser.
* "My records" filter on `context.user.id`, never on an id in `data`. A user id in `data` can name someone
  else, like a task's assignee, but never decides what the caller may see or change.
* A `publicFn` returns only what a visitor should see: map rows to the fields the page shows rather than
  returning whole records.
* A `publicFn` that reads `context.user` returns early when it's null (`if (!context.user) return [];`)
  before filtering on it. A filter value of `undefined` is dropped, so
  `filters: { createdBy: context.user?.id }` matches every row.

### The signed-in user

`context.user` has this shape (`User`, exported by `zitejs/start`):

```typescript theme={"system"}
type User = {
  id: string;
  email: string;
  name: string;
  firstName?: string;
  lastName?: string;
  image: string | null; // their photo's URL, or null
  emailVerified: boolean;
  createdAt: Date;
  updatedAt: Date;
  roles: ReadonlyArray<{ id: string; name: string }>;
  isInternal: boolean;
};
```

Put `context.user.id` in a `user` field to record who a row belongs to. A `user` or linked-record field
reads back as an array of ids, so test it with `[row.owner ?? []].flat().includes(context.user.id)`, never
`===`.

### Errors

For an expected failure, throw a `ZiteError` from `zitejs/start`:

```typescript theme={"system"}
throw new ZiteError('NOT_FOUND', 'No such request');
```

The code comes first and sets the HTTP status, and the message reaches the page:

| Code | Status |
| - | - |
| `'BAD_REQUEST'` | 400 |
| `'UNAUTHORIZED'` | 401 |
| `'FORBIDDEN'` | 403 |
| `'NOT_FOUND'` | 404 |
| `'CONFLICT'` | 409 |
| `'RATE_LIMITED'` | 429 |

Any other error reaches the page with its own message and status 500, with credentials redacted. Keep
internal detail out of error messages and `console.error` it instead. To show visitors different words than
the logs get, pass an options object:

```typescript theme={"system"}
throw new ZiteError({
  code: 'CONFLICT',
  message: `Slot ${data.slotId} is already booked`,
  userFacingMessage: 'That slot was just taken',
});
```

## Pages and loaders

`src/routes/` holds the pages, one file per route: `index.tsx` is `/`, `customers/$id.tsx` is
`/customers/:id`, and a file or folder named `_name` is a layout that wraps the routes inside it without
adding to the URL. Each file exports `export const Route = createFileRoute('/customers/$id')({ ... })` from
`@tanstack/react-router`, with the path matching the file's.

```tsx theme={"system"}
// src/routes/_app/requests.tsx
import { createFileRoute } from '@tanstack/react-router';
import { queryOptions, useMutation, useQueryClient, useSuspenseQuery } from '@tanstack/react-query';
import { toast } from 'sonner';
import { Button } from '@project/components/ui/button';
import { closeRequest, listMyRequests } from '../../lib/requests.functions';

const myRequests = queryOptions({
  queryKey: ['requests', 'mine'],
  queryFn: () => listMyRequests(),
});

export const Route = createFileRoute('/_app/requests')({
  head: () => ({ meta: [{ title: 'My requests' }] }),
  loader: ({ context }) => context.queryClient.query(myRequests),
  component: Requests,
});

function Requests() {
  const { data: requests } = useSuspenseQuery(myRequests);
  return <ul>{requests.map(request => <RequestRow key={request.id} request={request} />)}</ul>;
}

function RequestRow({ request }: { request: { id: string; title: string; done: boolean } }) {
  const queryClient = useQueryClient();
  const close = useMutation({
    mutationFn: () => closeRequest({ data: { id: request.id } }),
    // Returning the refetch keeps the mutation pending until the list shows the change.
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['requests'] }),
    onError: error => toast.error(error.message),
  });
  return (
    <li>
      {request.title}
      {!request.done && !close.isPending && <Button onClick={() => close.mutate()}>Resolve</Button>}
    </li>
  );
}
```

* A page's data lives in TanStack Query. Each read is a `queryOptions` whose `queryKey` starts with the
  table it reads, then every input (`['customers', 'list', { status }]`, `['customers', 'detail', id]`), so
  rows loaded for other inputs never show. The loader's `context.queryClient.query(...)` sends the first
  page with its data, and the component reads it with `useSuspenseQuery`. A later visit fetches again only
  when a write invalidated the query or it's older than 30 seconds, so a changed list never flashes its old
  rows.
* With params: `loader: ({ context, params }) => context.queryClient.query(customerQuery(params.id))`. For
  a missing record the server function returns null, and the loader throws `notFound()` from
  `@tanstack/react-router` so the route's `notFoundComponent` shows.
* For search params, use `validateSearch` with a zod schema, then `Route.useSearch()`. A loader takes the
  ones it uses through deps: `loaderDeps: ({ search }) => ({ status: search.status })`, then
  `loader: ({ context, deps }) => context.queryClient.query(customersQuery(deps.status))`.
* A loader awaits only what the page can't show without. A read that's slow next to the rest, like a chart
  over many rows or a call to an outside service, starts in the loader without being awaited
  (`void context.queryClient.query(statsQuery).catch(() => {})`). The component that reads it sits in its
  own `<Suspense>` with a skeleton of that part as its fallback, inside an `ErrorBoundary` from
  `react-error-boundary` whose `onReset` is `reset` from `useQueryErrorResetBoundary()` and whose fallback
  offers a retry, so a failed read replaces only that part. A read about as quick as the page's own is
  awaited with it (`Promise.all` in the loader).
* A write is a `useMutation` whose `onSuccess` invalidates by the table (`queryKey: ['customers']`),
  refreshing every list and detail of it. Where a click should answer at once, like a checkbox, a toggle or
  a status change, show the change while the mutation is pending (`variables` holds what it's changing
  to) and toast its error. Where several places show that value, set them in `onMutate` with
  `queryClient.setQueryData` and put the old data back in `onError`. A form keeps its input until the write
  succeeds, clearing or closing in `onSuccess`. A `useMutation` tracks only its latest call, so each row of
  a list gets its own.
* `head()` sets the page's title and meta tags, and `headers()` its response headers.
* Navigate with `<Link to="/customers/$id" params={{ id }}>` and `useNavigate()` from
  `@tanstack/react-router`.
* The router supplies error screens (in the editor's preview, the error screen offers to fix the error) and
  keeps the current page on screen while the next one loads. Give a page that loads data a
  `pendingComponent`, a skeleton of its own layout, which the router shows once a load passes a second, and
  a route its own `errorComponent` where it needs one.
* `defaultPreload: 'intent'` in `src/router.tsx` loads a linked page, its loader included, when the link is
  hovered. Change it there for the whole app, or with `preload` on a `<Link>`.

The edge caches a page only when its route asks with `Cache-Control: public, s-maxage=<seconds>` (up to a
day), and only for visitors who aren't signed in. A publish or a settings change starts it fresh within
seconds, though each edge location may serve the old page once more.

To keep pages for signed-in people only, guard them with a layout route. See
[Access and sign-in](https://developers.zite.com/framework/access-and-sign-in.md#guarding-pages).

## Where code runs

Loaders and `beforeLoad` run on the server for the first page and in the browser after that, so they reach
data only by calling server functions. Components render on the server too, except under an
`ssr: 'data-only'` layout (see [Access and sign-in](https://developers.zite.com/framework/access-and-sign-in.md#guarding-pages)). `zite.*`, `integrations.get`, email, `ZiteMeta`, and
`process.env` are server-only: use them inside a server function's handler or a `*.server.ts` helper, never
at a route file's top level or in a component.

* Code that needs the browser (`window`, `localStorage`, `navigator`, maps, cameras, rich editors, form
  embeds) runs in `useEffect` or an event handler, or inside `<ClientOnly fallback={...}>` from
  `@tanstack/react-router`. A page that is browser-only throughout can set `ssr: false` on its route.
* The server renders in UTC. A date or time shown in the visitor's own zone (date-fns `format`,
  `toLocaleString`, `Intl.DateTimeFormat` without a `timeZone`), or anything read from the clock ("5
  minutes ago"), comes out differently in the browser, and React reports a hydration mismatch. Render it
  inside `<ClientOnly>`, or format with an explicit `timeZone`.
* Read `process.env` inside handlers, not at module scope.
* Keep no module-level mutable state (caches, counters, a module-scope `QueryClient`) in server code: one
  instance serves many visitors at once.

## Libraries

These are already installed. Use them for their jobs:

* shadcn/ui components from `@project/components/ui/*`, for example
  `import { Button } from '@project/components/ui/button'`. Write a custom component only when one doesn't
  exist.
* `@project/components/ui/table`, powered by `@tanstack/react-table`, for tables.
* `@tanstack/react-table` for headless sortable, filterable, and paginated table logic (compose it with
  `@project/components/ui/table` for the styled HTML).
* tailwindcss for styling.
* recharts for charts and graphs.
* lucide-react for icons.
* framer-motion for animations.
* zod for validation. It's zod 4, so a custom message is `{ error: '...' }`.
* date-fns for dates.
* react-hook-form, optionally, for custom forms.
* use-debounce for debouncing calls to server code.
* react-webcam for the device camera in React components.
* barcode-detector for scanning barcodes and QR codes from the camera feed.
* `@dnd-kit/core`, `@dnd-kit/sortable`, and `@dnd-kit/utilities` for drag and drop and sortable lists.

The app's `package.json` lists what's already installed, so reach for those first. For anything else,
install it into the app, since the workspace root and the app are separate packages:

```bash theme={"system"}
npm install <pkg> -w apps/<appDir> --ignore-scripts
```

The sandbox is a real npm workspace with network access, and the manifest npm writes is committed with your
other changes. Pass `--ignore-scripts`: a package's install hooks run before anything reviews them. Leave
`zitejs` out of installs, since the platform pins it.

### Server code runs in a Worker

Server code runs on Cloudflare Workers, not Node. A library that needs `fs`, native streams, or a Node-only
entry point bundles cleanly and then fails when it's called, so reach for browser and ESM-friendly libraries.

Workers load the app's whole server bundle into every new instance. Each megabyte adds about 100 ms to the
request that starts one, and a deploy over 64 MiB is refused. In server code, use the smallest package that
does the job:

| Job | Use | Not |
| - | - | - |
| Google APIs | The package for the API you call: `@googleapis/sheets`, `@googleapis/drive`, `@googleapis/calendar`, `@googleapis/gmail` | `googleapis`, which bundles every Google API (12 MB) |
| AWS | The v3 client for the service, such as `@aws-sdk/client-s3` | `aws-sdk` v2, which is 10 MB and fails on Workers |
| HTML parsing | `linkedom` or `cheerio` | `jsdom`, which needs Node |
| PDFs | `pdf-lib` to create or fill them, `unpdf` to read their text | |
| Firestore | Its REST API through `fetch` | `firebase-admin`, which can't load on Workers |
| OCR and local ML models | A hosted API | Anything that runs the model locally: they need full Node |

Data an app ships with, such as a catalog, an archive, or a large lookup table, goes in the database, or in
`public/` as a JSON file pages fetch. Importing it compiles it into the server bundle too.

## Background work

Work on a schedule (anything time-based, recurring, or set for a future time: "every Monday at 9am", "a daily
digest", "every 5 minutes", "remind me in 7 days") is an automation on a schedule
(`on: { type: 'schedule', ... }`), never a `setInterval`
or `setTimeout` loop. The Worker running a loop restarts at any time, and the loop stops for good. See
[Schedules](https://developers.zite.com/automations/schedules.md).

Work that runs when something posts to a URL, from a sender you set up yourself (a Zapier or Make step, a
form tool, a webhook added in a service's dashboard), is an automation on a webhook (`on: { type: 'webhook' }`). See
[Webhooks](https://developers.zite.com/automations/webhooks.md). For changes to the workspace's tables and events in connected
services, see [Triggers](https://developers.zite.com/automations/triggers.md).

> [!NOTE]
>
> Schedules need the Business plan.

## API routes

An API route is for when a URL is itself the product: a JSON feed, a file download, a URL another service
calls. API routes live under `src/routes/api/` with `server.handlers`. Pages call server functions instead.
See [API routes](https://developers.zite.com/framework/api-routes.md), which also covers server functions that stream.

## Environment variables

Server code reads environment variables from `process.env`. Declared variables (`ZITE_APP_URL` and the
secrets you've configured) are typed as `string` and set at runtime, so use them directly, without `??`
fallbacks.

`process.env.ZITE_APP_URL` is the public URL of the current app: `https://my-app.zite.so`, or the app's
custom domain if it has one. Use it whenever you link back to the app, and never hardcode the app's URL:

* Email links ("View in app" buttons).
* Slack or Teams notification links.
* Shareable record URLs, such as `${process.env.ZITE_APP_URL}/records/${recordId}`.

API keys for services with no integration are secrets: `UPPER_SNAKE_CASE` names that start with `ZITE_`,
read as `process.env.ZITE_STRIPE_SIGMA_API_KEY`. A secret that hasn't been added yet leaves its variable
unset, so check it before use and throw a `ZiteError` naming it. See
[Secrets and integrations](https://developers.zite.com/framework/secrets-and-integrations.md).

## Links into the workspace

Links into Zite itself (the workspace home, an "Edit in Zite" button, help pages that send someone to the
editor) come from `ZiteMeta.getWorkspace()`, called from server code:

```typescript theme={"system"}
import { ZiteMeta } from 'zitejs/meta';

const { workspaceHomeUrl, editorUrl, appPublicIdentifier, projectPublicIdentifier } =
  await ZiteMeta.getWorkspace();
```

Never hardcode `/editor/zite/...`, `/workspace/...`, or a Zite host: after a listing is cloned, those URLs
still point at the source workspace. Links into the live app stay on `process.env.ZITE_APP_URL`.

## Integrations

Server code calls connected services, and the frontend never touches integrations directly. There is no
built-in AI helper in the framework: AI features go through the `openai`, `anthropic`, or `gemini`
integration. See [Secrets and integrations](https://developers.zite.com/framework/secrets-and-integrations.md) and
[Email](https://developers.zite.com/framework/email.md).

## Checking that it works

A clean `check_app` doesn't prove server functions work. Try key queries and integration calls in
`run_one_off_script`, then read the server functions' runs with `get_logs` for errors.
`run_one_off_script` runs outside the Start app, so a script can't call the app's server functions: it
reaches data and integrations directly through `zitejs/db` and `zitejs/integrations`. It runs against the
live database, so anything it seeds is real data. See [Build tools](https://developers.zite.com/mcp/build-tools.md).

## Where to next

* [Project structure](https://developers.zite.com/framework/project-structure.md): where everything lives, and which files the
  platform owns.
* [Database](https://developers.zite.com/framework/database.md): the `zite` client, its limits, and SQL.
* [Access and sign-in](https://developers.zite.com/framework/access-and-sign-in.md): access modes, guarded pages, and sign-in.
* [API routes](https://developers.zite.com/framework/api-routes.md): URLs that are the product, and streaming.
* [File uploads](https://developers.zite.com/framework/file-uploads.md): uploading, storing, and serving files.
* [Email](https://developers.zite.com/framework/email.md): sending email from server code.
* [Secrets and integrations](https://developers.zite.com/framework/secrets-and-integrations.md): connected services and API keys.
* [App config](https://developers.zite.com/framework/app-config.md): every `zite.config.json` field, and sign-in hooks.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.