Files
sweet/docs/canary/concepts/middleware.md
T
Christian Svensson 24c86ea20e fix: correct anchors by using heading text only (#3167)
Addresses the issue mentioned in
https://github.com/denoland/fresh/pull/3163#discussion_r2246708003.

The issue was that the `raw` markdown was being used for e.g. `## My
title`, thus the slug became `-my-title` instead of `my-title`. Slugs
were working correctly for `codespan` in headers, e.g. ``## `someCode`
``.

I decided to hard error if unexpected heading syntax is used over
sluggifying unexpected content (can become super weird otherwise, e.g.
`## <button ...>My heading</button>`). I can revert to fallbacking to
`raw` if preferred, but perhaps with at least trimming leading `-` just
in case.
2025-08-01 12:46:12 +02:00

90 lines
2.4 KiB
Markdown

---
description: |
Add middleware routes to intercept requests or responses for analytics purposes, access control, or anything else.
---
A middleware is a function that receives a [`Context`](/docs/canary/context)
object with the
[`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) and
returns a
[`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response). They
are typically used to set HTTP Headers, measure response times or fetch data and
pass it to another middleware.
```tsx main.ts
const app = new App<{ greeting: string }>()
.use((ctx) => {
// Middleware to pass data
ctx.state.greeting = "Hello world";
return ctx.next();
})
.use(async (ctx) => {
// Middleware to add a HTTP header
const res = await ctx.next();
res.headers.set("server", "fresh server");
return res;
})
// A handler is a form of middleware that responds. Here we
// render HTML and return it.
.get("/", (ctx) => {
return ctx.render(<h1>{ctx.state.greeting}</h1>);
});
```
Middlewares can be chained and combined in whatever way you desire. They are an
excellent way to make http-related logic reusable on the server.
## Middleware helper
Use the `define.middleware()` helper to get typings out of the box:
```ts middleware/my-middleware.ts
import { define } from "./utils.ts";
const middleware = define.middleware(async (ctx) => {
console.log("my middleware");
return await ctx.next();
});
```
## Included middlewares
Fresh ships with the following middlewares built-in:
- [cors()](/docs/canary/plugins/cors) - Set CORS HTTP headers
- [csrf()](/docs/canary/plugins/cors) - Set CSRF HTTP headers
- [trailingSlash()](/docs/canary/plugins/trailing-slashes) - Enforce trailing
slashes
## Filesystem-based middlewares
With file system based routing you can define a middleware in a `_middleware.ts`
file inside the `routes/` folder or any of it's subfolders.
```ts routes/foo/_middleware.ts
import { define } from "./utils.ts";
export default define.middleware(async (ctx) => {
console.log("my middleware");
return await ctx.next();
});
```
You can also export an array of middlewares:
```ts routes/foo/_middleware.ts
import { define } from "./utils.ts";
const middleware1 = define.middleware(async (ctx) => {
console.log("A");
return await ctx.next();
});
const middleware1 = define.middleware(async (ctx) => {
console.log("B");
return await ctx.next();
});
export default [middleware1, middleware2];
```