Middleware
Per-route middleware
Add middleware by path, to a whole table, or to one route
// for every route in the table
export const = ("/admin", { : [] })({
"GET /me": (, ) => ({ : .get("user") }), // only for this route
"DELETE /users/:id": ({ : [] }, async ({ }) => {
await ();
return { : };
}),
});
const = ();
.();Ways to add it
| Write | Runs for |
|---|---|
app.use(mw) | Every request |
app.use("/admin", mw) | /admin and below |
defineRoutes(prefix, { use: [mw] }) | The routes in that table |
endpoint({ use: [mw] }, handler) | That route only |
Middleware in a table's or a route's use runs only for requests that matched that route. For a table without a prefix, write defineRoutes("", { use }).
Order
- The app's
app.use() - The table's
use - The route's
use - Checking the schemas (reading the body)
- The handler
If middleware returns a value, it stops before the schemas are checked. The body of a request that fails authentication is not read.
Types
Put middleware written as Middleware<{ user: User }> in use, and c.get("user") is typed in that route.
Raise a limit
It also raises the default body limit (1 MiB) on one route only.
const = ({
"POST /import": ({ : [({ : 20 * 1024 * 1024 })] }, async (, ) => {
const = await ..();
return { : .length };
}),
});