---
title: Interceptors
description: Run code around every request the app serves.
---

An interceptor wraps every request, for app-wide work such as API keys, CORS,
rate limits or logging. For per-route logic with typed context, use
[middleware](/docs/middleware).

```ts
import { createApp, interceptor } from "@rest-rpc/server";

const logging = interceptor(async ({ request, route, next }) => {
	const response = await next();
	console.log(request.method, route?.path, response.status);
	return response;
});

export default createApp(router, { interceptors: [logging] });
```

```ts
type Interceptor = (args: {
	request: Request;
	/** The matched route's definition, or `undefined` when none matches. */
	route: InterceptedRoute | undefined;
	/**
	 * What the runtime passed after the request, such as Cloudflare Workers'
	 * `env`. Untyped: `const [env] = args as [Env]`.
	 */
	args: readonly unknown[];
	/**
	 * Runs the later interceptors and the route. Pass a request to continue
	 * with it instead, keeping its URL and method.
	 */
	next: (request?: Request) => Promise<Response>;
}) => Response | Promise<Response>;
```

- Interceptors run in order, the first outermost, after the route is matched
  and before anything else, including the `context` function.
- They run for unmatched requests too, but not for
  [static routes](/docs/route-builder#static-responses).
- Return a `Response` without calling `next()` to answer the request
  yourself, or throw to send an error.
- `next()` resolves when the response starts, before a streamed body is sent.

## Errors

`next()` rejects with any error thrown after the interceptor, including
`NOT_FOUND` and request validation failures. A response that fails validation
rejects with `INTERNAL_SERVER_ERROR`, with the issues as its `cause`.

What no interceptor catches is sent as an [error response](/docs/errors). To
make earlier interceptors see error responses instead of rejections, such as
for CORS headers, catch with `errorResponse`:

```ts
import { createApp, errorResponse, interceptor } from "@rest-rpc/server";

createApp(router, {
	interceptors: [
		cors, // receives error responses too
		interceptor(({ next }) => next().catch(errorResponse)),
		apiKey,
	],
});
```

:::note
An error an interceptor throws isn't checked against the route. To send an
error the route defines, throw the route's own error class.
:::

### Report Errors

`onError()` creates an interceptor that calls back with every error thrown
after it, including a stream that fails after it started, and rethrows it.
Place it after interceptors that turn errors into responses:

```ts
import { onError } from "@rest-rpc/server";

const report = onError((error, { request, route }) => {
	logger.error({ method: request.method, path: route?.path, error });
});
```

## Node

Import `interceptor`, `onError` and `writeErrorResponse` from
`@rest-rpc/server/node`. Node interceptors write to the `ServerResponse`
instead of returning a `Response`:

```ts
import {
	createApp,
	interceptor,
	writeErrorResponse,
} from "@rest-rpc/server/node";

const requestId = interceptor(({ response, next }) => {
	response.setHeader("x-request-id", crypto.randomUUID());
	return next();
});

const sendErrors = interceptor(({ response, next }) =>
	next().catch((error) => {
		if (response.headersSent) throw error;
		return writeErrorResponse(response, error);
	}),
);
```

- Headers set before `next()` are sent with every response, errors included.
- `next()` resolves once the response is written, and rejects when a stream
  fails after it started.
- A written response can't change. To answer the request yourself, write
  the response and don't call `next()`.
- `onError` reports bodies that fail while streaming. On Fetch, it only
  reports failing Server-Sent Events streams.
