# API routes

> Web-standard endpoints, colocated with your pages, with no configuration.

An API route answers a caller that isn't your own pages: a webhook, an OAuth
callback, a health check, a mobile app. A `route.ts` sits in the same
`src/app` tree as your pages, and its URL comes from its folder:

```ts title="src/app/api/health/route.ts"
export function GET(request: Request): Response {
  return Response.json({ ok: true, at: new Date().toISOString() })
}
```

`GET /api/health` now answers. The export name is the method, the argument is
an ordinary `Request`, and you return a `Response`. It runs the same way on Bun,
Node and Cloudflare Workers.

For your own client, a [query](/guides/queries/) reads data and a
[server action](/guides/server-actions/) writes it, both typed with no
endpoint to write. Use an API route when the caller can't import your
functions.

## Handling methods

Export one function per method: `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD`
or `OPTIONS`.

```ts title="src/app/api/echo/route.ts"
export async function POST(request: Request): Promise<Response> {
  const body = (await request.json()) as { name?: string }

  if (!body.name) return Response.json({ error: 'name is required' }, { status: 422 })

  return Response.json({ greeting: `Hello, ${body.name}` }, { status: 201 })
}

export function GET(): Response {
  return Response.json({ usage: 'POST { "name": "…" }' })
}
```

```
POST /api/echo  {"name":"Ada"} → 201 {"greeting":"Hello, Ada"}
POST /api/echo  {}               → 422 {"error":"name is required"}
GET  /api/echo                   → 200 {"usage":"POST { \"name\": \"…\" }"}
PUT  /api/echo                   → 405  Allow: GET, POST, HEAD
```

- A method you didn't export is answered **405**, with an `Allow` header naming
  the ones you did.
- `HEAD` is answered by your `GET` with the body stripped.
- A `route.ts` that exports no method fails the build.

Read the body with the web API: `request.json()`, `.formData()`, `.text()`.

## Dynamic segments

`[name]` and `[...rest]` work as they do for [pages](/guides/routing#dynamic-segments).
The values arrive in the second argument as a promise. Type it with
`RouteContext` and the route's pattern:

```ts title="src/app/api/greet/[name]/route.ts"
import type { RouteContext } from '@rsc-kit/core/route-schema'

export async function GET(request: Request, { params }: RouteContext<'/api/greet/[name]'>) {
  const { name } = await params

  return Response.json({ greeting: `Hello, ${name}` })
}
```

```
GET /api/greet/ada → {"greeting":"Hello, ada"}
```

The pattern is checked against your routes, so a typo fails the typecheck, and
so does reading `params.name` without the `await`.

- `RouteHandler<'/api/greet/[name]'>` types the whole function instead:
  `export const GET: RouteHandler<…> = async (request, { params }) => …`.
- With a [`params` schema](/guides/url-validation), `RouteContext<typeof params>`
  types them from its output.
- A static segment beats a dynamic one: `/api/user/me` is answered by
  `me/route.ts`, not `[id]/route.ts`.

## Guarding a route

A route runs the `middleware.ts` files above it, as a page in that folder
would, so an endpoint under a guarded path needs no second check.
See [Authorization](/guides/authorization/#protect-an-api-route).

A refusal answers code that fetched the route with a `401` or `403` and the
destination in `X-RSC-Redirect`, rather than a redirect `fetch` would follow
to a login page. A browser that navigated to the route gets a real `Location`.

A `redirect()` thrown from the handler is the route's own answer, a real `3xx`
for whoever asked. `notFound()` answers `404`.

## Posts from another site

A `POST`, `PUT`, `PATCH` or `DELETE` that a browser sends from another site is
answered **403** before your handler runs. Otherwise any page on the web could
post a form to your route with your visitor's cookies. The browser's
`Sec-Fetch-Site` header says where the request came from, and an older
browser's `Origin` is compared with your host. Actions and forms follow the
same rule.

A caller that isn't a browser, such as a webhook, a cron job or another server,
sends neither header and is never refused. To let a browser app on another
origin post, name it:

```ts title="vite.config.ts"
rscKit({ trustedOrigins: ['https://admin.example.com'] })
```

`GET`, `HEAD` and `OPTIONS` are answered from anywhere.

### An api other sites call

When other sites post to a route from the browser, and their origins live in
your database rather than in config, such as a chat widget embedded on your
customers' pages, the route says so itself:

```ts title="src/app/api/v1/chat/route.ts"
export const crossOrigin = true

export async function POST(request: Request) {
  const key = request.headers.get('authorization') // the widget's own key
  // ...
}
```

Another site's request then reaches the handler **without the visitor's
cookies**: `cookies()`, `headers()`, `request` and any backend call see none,
and a guard that reads the session finds nobody. Your own site's requests keep
them.

- Authenticate with a key the caller sends, and check the `Origin` yourself if
  each key belongs to particular sites.
- Answering the browser's CORS preflight, with an `OPTIONS` export, is still
  the route's job.
- `crossOrigin` must be the literal `true` or `false`: the build reads it from
  the source.

## The build answers what it can

The build calls every `GET` once. A route that answers without reading the
request is stored, status and headers included, and served from disk, like a
page:

```text
  ○  /api/health
  ○  /api/pricing
  ƒ  /api/me
     reads the request — headers
  ƒ  /api/posts/_id_
     one url per param value, and none are listed
```

Reading the request makes a route run per request:

```ts
export async function GET(request: Request) {
  const who = request.headers.get('Authorization')  // ƒ — per request
}
```

`cookies()`, `headers()` and `await connection()` do the same. Use
`connection()` to say it outright when nothing else in the route does.

A route runs per request when it:

- **reads the request:** headers, the body, the signal, or `request.url`. To
  read the query and stay storable, await `searchParams` instead of
  `new URL(request.url).searchParams`.
- **takes a parameter**, since the build doesn't know which values exist
- **sits under a `middleware.ts`**, since a guarded route answers differently
  per caller
- **sets a cookie**, which is an answer for one visitor
- **answers 4xx or 5xx to the build**, which sent no request to refuse
- **answers with bytes rather than text**, which is a file
- **does not finish**, usually because it was waiting on a request

A route that used `Date.now()` or `Math.random()` is stored with a warning, the
same one a page gets. `await connection()` makes it run per request.

### What is never stored

Only a `GET` is stored. A `POST`, `PUT`, `PATCH` or `DELETE` is something meant
to happen each time.

A request with a **query string** runs the route only if the route reads the
query. A stored route that never awaits `searchParams` serves its stored answer
for `?utm_source=anything`. Await it, or export a `searchParams` schema, and the
stored answer is kept for the bare URL alone. A route that reads the query off
`request.url` is not stored at all; the build output says
`reads the request — url` and what to await.

## A route that streams

`events()` turns an async generator into server-sent events. Each `yield` is a
message, sent the moment it happens:

```ts title="src/app/api/orders/[id]/events/route.ts"
import { events, named } from '@rsc-kit/core/events'

export const GET = events(async function* ({ params, signal }) {
  const { id } = await params

  for await (const status of orderStatus(id, { signal })) {
    yield { status }                                // one message per yield
  }

  yield named('closed', { id })                     // a message with a name
})
```

It is an ordinary `route.ts`: it runs the `middleware.ts` above it and takes the
same params.

- Each yield is sent as JSON.
- A keepalive goes out every eight seconds so a proxy doesn't drop an idle
  stream. [`RSC_STREAM_KEEPALIVE_MS`](/hosts/deployment#streams-and-idle-timeouts)
  changes it.
- The response is `text/event-stream`, `no-store, no-transform`, and never
  compressed. A stream is never stored, whatever it reads.
- The generator ends when the browser goes away; that is what `signal` is for.
- `named(event, data, { id })` names a message or gives it an id, for a client
  that listens by name or resumes after a reconnect.

### Reading a stream in a component

```tsx
'use client'

import { useEvents } from '@rsc-kit/core/useEvents'

export function OrderStatus({ id, initial }: { id: string; initial: { status: Status } }) {
  const { latest, status } = useEvents(`/api/orders/${id}/events`)
  const current = latest ?? initial            // the server-rendered value until the first message

  return (
    <p>
      {current.status}
      {status === 'connecting' && <Spinner />}
    </p>
  )
}
```

`latest` is the last message and `all` is every message so far. Pass `event` to
read only the messages with that name:

```tsx
const closed = useEvents(`/api/orders/${id}/events`, { event: 'closed' })
// closed.latest: { id: string } | null
```

Messages are typed from the route: `latest` is what the generator yields, and
a route that changes what it sends fails the typecheck where the hook reads it.
A URL no route answers does not compile. For a stream with no type to read,
such as another site's, name it: `useEvents<Message>(url)`.

To keep the value in your own state, a reducer or a cache library, pass
`onMessage`:

```tsx
const [order, setOrder] = useState(initial)
useEvents(`/api/orders/${id}/events`, { onMessage: setOrder })           // useState

useEvents(`/api/orders/${id}/events`, { onMessage: (m) => dispatch({ type: 'update', m }) })

useEvents(`/api/orders/${id}/events`, {
  onMessage: (m) => queryClient.setQueryData(['order', id], m),                // TanStack
})
useEvents(`/api/orders/${id}/events`, {
  onMessage: (m) => mutate(['order', id], m, false),                           // SWR
})
```

### Reconnecting

The hook reconnects on its own. The browser's `EventSource` reconnects after a
dropped connection, resuming with `Last-Event-ID` when you yielded ids. After an
error answer, such as a 502 during a deploy, the browser gives up, so the hook
opens a new connection, waiting a second, then two, then four, up to thirty, and
at once when the browser comes back online.

`status` says where it is, `error` holds the last error, and `close()` stops
it. `onError` fires when it happens, for a notice rather than a retry:

```tsx
useEvents(`/api/orders/${id}/events`, {
  onMessage: setOrder,
  onError: () => toast('Reconnecting…'),
})
```

`useEvents` subscribes in an effect, so it is safe in a component that also
renders on the server.

### Streaming or polling

A stream sends bytes only when something changed, which is far cheaper per
update than [polling a query](/guides/queries/#live-data). It costs an open
connection per tab: fine on Bun or Node, a limit on a Worker or a small
container behind a load balancer. It needs a source of changes to yield from,
such as a database listener, a queue or a timer; a generator that polls the
database itself has only moved the polling. Start with polling when you have no
change feed or your host holds few connections.
