---
title: Middleware and Context
description: Run code around handlers, pass values to them, and describe routes with metadata.
---

Middleware runs around a route's handler, for guards, transactions, timing or
caching. It receives the same arguments as the handler and passes values to
it through `context`.

## Add Middleware

```ts
const profile = route
	.$context<{ headers: Headers }>()
	.get("/profile")
	.error("UNAUTHORIZED", { status: 401 })
	.use(async ({ next }) => {
		const started = performance.now();
		try {
			return await next();
		} finally {
			console.log(performance.now() - started);
		}
	})
	.use(async ({ context, errors, next }) => {
		const user = await authenticate(context.headers.get("authorization"));
		if (!user) throw errors.UNAUTHORIZED();
		return next({ context: { user } });
	})
	.handler(({ context }) => context.user);
```

- Middleware runs after the request is validated, in the order it's added.
- `next()` runs the rest of the chain and returns its response. Call it at
  most once.
- Return the response from `next()`, or `respond()` to answer without running
  the handler. Returning anything else is a type error.
- Define request schemas and errors before `.use()` for middleware to see
  their types.
- Errors thrown later in the chain come out of `next()`, so `try`/`finally`
  works.

:::note
A streamed body is sent after the chain returns, so code after `next()` runs
before a stream finishes.
:::

## Context

`context` holds two kinds of values:

- **Initial context**: values the server provides for every request, such as a
  database client or the native request. Declare them with `$context<T>()`.
- **Injected context**: values middleware adds with `next({ context })`,
  typed for everything after it.

```ts
const base = route.$context<{ db: Db; headers: Headers }>();

const withSession = base.use(async ({ context, next }) => {
	const user = await findSession(
		context.db,
		context.headers.get("authorization"),
	);
	return next({ context: { user } }); // user: User | undefined
});

const profile = withSession
	.get("/profile")
	.handler(({ context }) => context.user);
```

The server passes initial context with its `context` option, as values or a
function of the request:

```ts
createApp(router, {
	context: async (request) => ({ db, headers: request.headers }),
});
```

- The option is required, and type-checked, when any route declares initial
  context.
- [Framework handlers](/docs/server/framework-integration) take it per request.

To require the same initial context on every route, augment `DefaultContext`:

```ts
declare module "@rest-rpc/server" {
	interface DefaultContext {
		db: Db;
	}
}
```

## Respond and Catch

Middleware can answer by itself with `respond()`, or turn errors from your own
code into the route's errors:

```ts
const list = route
	.get("/posts")
	.response(z.array(postSchema))
	.use(({ respond, next }) => (isPaused() ? respond([]) : next()))
	.handler(() => findPosts());

const withUserNotFound = route.error(UserNotFound).use(async ({ next }) => {
	try {
		return await next();
	} catch (error) {
		if (error instanceof RecordNotFound) {
			throw new UserNotFound({ data: { id: error.id }, cause: error });
		}
		throw error;
	}
});
```

- `respond()` in middleware takes the statuses defined before it, so define
  the responses of a route whose middleware responds.
- What middleware returns is validated and sent the same way as a handler's
  response.

## Reuse Middleware

`route.middleware()` defines middleware once to add to many routes:

```ts
const transaction = route.middleware(({ next }) =>
	db.transaction(() => next()),
);

const list = route
	.use(transaction)
	.get("/posts")
	.handler(() => listPosts());
```

Reusable middleware is typed by the builder it's defined on. It can only be
added to routes that have its request schemas, errors and metadata:

```ts
const Unauthorized = routeError("UNAUTHORIZED", { status: 401 });

const attachUser = route
	.$context<{ db: Db }>()
	.headers(z.object({ authorization: z.string() }))
	.error(Unauthorized)
	.middleware(async ({ headers, errors, next, context }) => {
		const user = await authenticate(context.db, headers.authorization);
		if (!user) throw errors.UNAUTHORIZED();
		return next({ context: { user } });
	});

const profile = route
	.headers(z.object({ authorization: z.string() }))
	.error(Unauthorized)
	.use(attachUser) // the route now requires `db` from the server
	.get("/profile")
	.handler(({ context }) => context.user);
```

- Context the middleware reads that the route doesn't have yet becomes
  initial context the server has to provide.
- To require request fields without defining schemas, pass them as a type:
  `route.middleware<{ headers: { authorization: string } }>(...)`.

## Metadata

Metadata is how a route describes itself to code that runs on many routes,
such as an access check in middleware or an
[OpenAPI transform](/docs/tooling/openapi#transform-operations). Declare its shape
with `$meta<T>()`, and set it with `.meta()`:

```ts
type Access = "public" | "signed-in" | "posts:write";

const base = route.$meta<{ access: Access }>().use(({ route, next }) => {
	checkAccess(route.meta?.access);
	return next();
});

base.get("/health").meta({ access: "public" });
base.post("/posts").meta({ access: "posts:delete" }); // type error
```

- Repeated `.meta()` calls are merged.
- Reusable middleware, and middleware added before `.meta()`, see
  `route.meta` as `Partial<T> | undefined`, since a route may set any keys or
  none.

To use one shape for every route, augment `DefaultMeta` instead. Augment
`@rest-rpc/core` for routes defined with it:

```ts
declare module "@rest-rpc/server" {
	interface DefaultMeta {
		access: Access;
	}
}
```
