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 throughzitejs/* 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 azitejs factory, which decides who may call it:
signedInFn: only signed-in users, andcontext.useris aUser.publicFn: anyone, signed in or not, andcontext.userisUser | null. This is for external apps: an internal app signs everyone in first, so it usessignedInFnthroughout, and the build refuses apublicFnthere (public-in-internal).
methodis'GET'for reads and'POST'for writes.descriptionis 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 asdata. Callers pass{ data }even when every field is optional (fn({ data: {} })). Called with nothing, the validator getsundefinedand 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 thatconst: a server function returned from a helper or kept in an object fails when it’s called. - Raw
createServerFnfrom TanStack, or a factory of your own built on it, fails the build (raw-server-fn): access has to come fromzitejs. - Pages read through a query’s
queryFnand write through a mutation’smutationFn, 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.tshelper that each handler calls.
*.functions.ts(for examplesrc/lib/customers.functions.ts) exports the server functions pages call.*.server.tsholds 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:signedInFnproves only that someone is signed in. A function that takes a record id loads that record and checks it belongs tocontext.userbefore returning or changing it, because the id came from the browser.- “My records” filter on
context.user.id, never on an id indata. A user id indatacan name someone else, like a task’s assignee, but never decides what the caller may see or change. - A
publicFnreturns only what a visitor should see: map rows to the fields the page shows rather than returning whole records. - A
publicFnthat readscontext.userreturns early when it’s null (if (!context.user) return [];) before filtering on it. A filter value ofundefinedis dropped, sofilters: { createdBy: context.user?.id }matches every row.
The signed-in user
context.user has this shape (User, exported by zitejs/start):
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 aZiteError from zitejs/start:
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
queryOptionswhosequeryKeystarts with the table it reads, then every input (['customers', 'list', { status }],['customers', 'detail', id]), so rows loaded for other inputs never show. The loader’scontext.queryClient.query(...)sends the first page with its data, and the component reads it withuseSuspenseQuery. 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 throwsnotFound()from@tanstack/react-routerso the route’snotFoundComponentshows. - For search params, use
validateSearchwith a zod schema, thenRoute.useSearch(). A loader takes the ones it uses through deps:loaderDeps: ({ search }) => ({ status: search.status }), thenloader: ({ 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 anErrorBoundaryfromreact-error-boundarywhoseonResetisresetfromuseQueryErrorResetBoundary()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.allin the loader). - A write is a
useMutationwhoseonSuccessinvalidates 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 (variablesholds what it’s changing to) and toast its error. Where several places show that value, set them inonMutatewithqueryClient.setQueryDataand put the old data back inonError. A form keeps its input until the write succeeds, clearing or closing inonSuccess. AuseMutationtracks only its latest call, so each row of a list gets its own. head()sets the page’s title and meta tags, andheaders()its response headers.- Navigate with
<Link to="/customers/$id" params={{ id }}>anduseNavigate()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 ownerrorComponentwhere it needs one. defaultPreload: 'intent'insrc/router.tsxloads a linked page, its loader included, when the link is hovered. Change it there for the whole app, or withpreloadon a<Link>.
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 andbeforeLoad 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 inuseEffector an event handler, or inside<ClientOnly fallback={...}>from@tanstack/react-router. A page that is browser-only throughout can setssr: falseon its route. - The server renders in UTC. A date or time shown in the visitor’s own zone (date-fns
format,toLocaleString,Intl.DateTimeFormatwithout atimeZone), 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 explicittimeZone. - Read
process.envinside 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 exampleimport { 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-tablefor headless sortable, filterable, and paginated table logic (compose it with@project/components/ui/tablefor 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/utilitiesfor drag and drop and sortable lists.
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:
--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 needsfs, 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 undersrc/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 fromprocess.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}.
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 the workspace
Links into Zite itself (the workspace home, an “Edit in Zite” button, help pages that send someone to the editor) come fromZiteMeta.getWorkspace(), called from server code:
/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 theopenai, anthropic, or gemini
integration. See Secrets and integrations and
Email.
Checking that it works
A cleancheck_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
- Project structure: where everything lives, and which files the platform owns.
- Database: the
ziteclient, its limits, and SQL. - Access and sign-in: access modes, guarded pages, and sign-in.
- API routes: URLs that are the product, and streaming.
- File uploads: uploading, storing, and serving files.
- Email: sending email from server code.
- Secrets and integrations: connected services and API keys.
- App config: every
zite.config.jsonfield, and sign-in hooks.