Skip to main content
An API route is for when a URL is itself the product: a JSON feed, a file download, a URL another service calls. Pages don’t need one: they call server functions instead. API routes are routes under src/routes/api/ that define server.handlers instead of a component.
For a URL that a service posts events to, from a sender someone sets up themselves (a Zapier or Make step, a form tool, a webhook added in a service’s dashboard), write an automation with a webhook instead.

Define an API route

Each handler is keyed by its HTTP method and returns a standard Response.

The contract

  • Every API route names who may call it in middleware, with one of these from zitejs/start: The build refuses a route without one (access-missing). An internal app signs everyone in first, so the build refuses anyone there (public-in-internal): use signedIn. See Access and sign-in for the two access modes.
  • staticData: { description } is one plain sentence on what the route does. It labels the route in the app’s Logic tab.
  • A bare dot in a route’s file name nests the path. settings.billing.tsx is /settings/billing, so a dot that belongs in the URL goes in brackets, as in my-orders[.]json.ts above, which serves /api/my-orders.json.
  • Some paths are the platform’s. Paths under /auth, /api/auth, /_zite, /__zite, /_serverFn and /cdn-cgi, and /manifest.webmanifest, are answered by the platform before the app. The build refuses a route there (reserved-path).

Cross-origin requests (CORS)

The platform adds no CORS headers. In an external app, a route that another site’s browser calls sets the CORS headers on its own responses, and answers the preflight in an OPTIONS handler. That handler needs anyone, since a preflight carries no cookies. To give methods their own access, pass handlers as a function and give each method its own middleware:
Another site gets only what anyone may. The platform never lets another site read a signed-in visitor’s answer, and it refuses that site’s cookie-carrying requests other than GET and HEAD. An internal app takes no cross-site calls.

Stream from a server function

A server function streams when its handler is an async generator: .handler(async function* ({ data }) { ... yield chunk; }). The page reads each chunk as it arrives, for example to show an AI reply while it’s written:
A thrown error’s message reaches the visitor mid-stream. Keep internal detail out of it, and console.error that detail instead.