Files
sweet/docs/canary/concepts/middleware.md
T
Christian Svensson b7f1abb0d0 test(docs): type check docs code examples (#3180)
This PR adds the initial seeds of type checking the code in all code
blocks for the Markdown Docs.

- Adds a unit test, disabled due to the many remaining errors, that can
help find incorrect code
- Fixes a bunch of syntax errors, type errors, and other code issues
found in the docs

## Future improvements

A lot of remaining issues is mostly related to missing imports, e.g.
`App`, `staticFiles`, `HttpError` etc. There's a couple of different
directions to solve this in future PR's.

- Add explicit imports to all docs examples (may become unnecessarily
verbose)
- Add code to docs code blocks, but with a hint to remove it when
rendering the markdown as HTML
   ```tsx
   import { App } from "fresh";
   // #docs-start

   // Everything above marker above is trimmed away
   const app = new App();
   ```
- Add a `types.d.ts` with "global" types used during type checking, so
globals, imports and so on can be handled globally

I do think that some examples probably should be more explicit with
imports, but it would be overkill for a lot of places such as `app.md`
and `context.md`.
2025-08-05 23:56:04 +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 middleware2 = define.middleware(async (ctx) => {
console.log("B");
return await ctx.next();
});
export default [middleware1, middleware2];
```