# Middlewares (/docs/core-concepts/middlewares)

Middlewares intercept HTTP requests and responses, enabling authentication, rate limiting, and other processing tasks.

Create a `src/middleware.ts` file to define your middleware:

```typescript title="src/middleware.ts"
import { type Middleware } from "xmcp";

const middleware: Middleware = async (req, res, next) => {
  const authHeader = req.headers.authorization;

  if (!customHeaderValidation(authHeader)) {
    res.status(401).json({ error: "Invalid API key" });
    return;
  }

  return next();
};

export default middleware;
```

<Callout variant="info">
  xmcp provides built-in middlewares for common tasks like [API key
  authentication](/docs/authentication/api-key) and [JSON web token
  authentication](/docs/authentication/jwt).
</Callout>

## Chaining middlewares

Define multiple middlewares as an array to chain them in sequence:

```typescript title="src/middleware.ts"
import { type Middleware } from "xmcp";

const middleware: Middleware = [
  async (req, res, next) => {
    // First middleware
    return next();
  },
  async (req, res, next) => {
    // Second middleware
    return next();
  },
];

export default middleware;
```

## Accessing headers

Use the `xmcp/headers` module to read request headers in your tools, prompts, or resources—useful for API keys, authentication tokens, and other custom headers.

```typescript title="src/tools/search.ts"
import { headers } from "xmcp/headers";

export default async function search({ query }: InferSchema<typeof schema>) {
  const requestHeaders = headers();
  const apiKey = requestHeaders["x-api-key"];

  const data = await fetchSomeData(apiKey);

  return JSON.stringify(data);
}
```
