|
| 1 | +--- |
| 2 | +title: createMiddleware |
| 3 | +--- |
| 4 | + |
| 5 | +`createMiddleware` creates a configuration object for SolidStart that specifies when middleware functions are executed during the request lifecycle. |
| 6 | + |
| 7 | +There are two lifecycle events available: `onRequest` and `onBeforeResponse`. |
| 8 | + |
| 9 | +- The `onRequest` event is triggered at the beginning of the request lifecycle, before the request is handled by the route handler. |
| 10 | +- The `onBeforeResponse` event is triggered after a request has been processed by the route handler but before the response is sent to the client. |
| 11 | + |
| 12 | +<Callout type="info" title="Note"> |
| 13 | + |
| 14 | +SolidStart will only execute the middleware functions if the path to the middleware file is configured within `app.config.ts` using the `middleware` option. |
| 15 | +This file must export the configuration using `export default`. |
| 16 | + |
| 17 | +</Callout> |
| 18 | + |
| 19 | +Learn more about middleware in the [Middleware documentation](/solid-start/advanced/middleware). |
| 20 | + |
| 21 | +## Parameters |
| 22 | + |
| 23 | +`createMiddleware` takes an object with the following keys: |
| 24 | + |
| 25 | +- `onRequest` (optional): A middleware function or an array of functions to execute at the `onRequest` event. |
| 26 | + If an array is provided, the middleware functions will be executed one by one, in the order they appear in the array. |
| 27 | +- `onBeforeResponse` (optional): A middleware function or an array of functions to execute at the `onBeforeResponse` event. |
| 28 | + If an array is provided, the middleware functions will be executed one by one, in the order they appear in the array. |
| 29 | + |
| 30 | +## Example |
| 31 | + |
| 32 | +```ts title="src/middleware/index.ts" |
| 33 | +import { createMiddleware } from "@solidjs/start/middleware"; |
| 34 | + |
| 35 | +export default createMiddleware({ |
| 36 | + onRequest: (event) => { |
| 37 | + console.log("Request received:", event.request.url); |
| 38 | + }, |
| 39 | + onBeforeResponse: (event) => { |
| 40 | + console.log("Sending response:", event.response.status); |
| 41 | + }, |
| 42 | +}); |
| 43 | +``` |
| 44 | + |
| 45 | +```ts title="app.config.ts" |
| 46 | +import { defineConfig } from "@solidjs/start/config"; |
| 47 | + |
| 48 | +export default defineConfig({ |
| 49 | + middleware: "src/middleware/index.ts", |
| 50 | +}); |
| 51 | +``` |
0 commit comments