Skip to main content
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.

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

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):
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:
The code comes first and sets the HTTP status, and the message reaches the page: 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:

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

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). 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:
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: 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. 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. For changes to the workspace’s tables and events in connected services, see Triggers.
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, 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. 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:
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 and Email.

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.

Where to next