Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add reference page for createMiddleware #1025

Merged
51 changes: 51 additions & 0 deletions src/routes/solid-start/reference/server/create-middleware.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
---
title: createMiddleware
---

`createMiddleware` creates a configuration object for SolidStart that specifies when middleware functions are executed during the request lifecycle.

There are two lifecycle events available: `onRequest` and `onBeforeResponse`.

- The `onRequest` event is triggered at the beginning of the request lifecycle, before the request is handled by the route handler.
- The `onBeforeResponse` event is triggered after a request has been processed by the route handler but before the response is sent to the client.

<Callout type="info" title="Note">

SolidStart will only execute the middleware functions if the path to the middleware file is configured within `app.config.ts` using the `middleware` option.
This file must export the configuration using `export default`.

</Callout>

Learn more about middleware in the [Middleware documentation](/solid-start/advanced/middleware).

## Parameters

`createMiddleware` takes an object with the following keys:

- `onRequest` (optional): A middleware function or an array of functions to execute at the `onRequest` event.
If an array is provided, the middleware functions will be executed one by one, in the order they appear in the array.
- `onBeforeResponse` (optional): A middleware function or an array of functions to execute at the `onBeforeResponse` event.
If an array is provided, the middleware functions will be executed one by one, in the order they appear in the array.

## Example

```ts title="src/middleware/index.ts"
import { createMiddleware } from "@solidjs/start/middleware";

export default createMiddleware({
onRequest: (event) => {
console.log("Request received:", event.request.url);
},
onBeforeResponse: (event) => {
console.log("Sending response:", event.response.status);
},
});
```

```ts title="app.config.ts"
import { defineConfig } from "@solidjs/start/config";

export default defineConfig({
middleware: "src/middleware/index.ts",
});
```
5 changes: 3 additions & 2 deletions src/routes/solid-start/reference/server/data.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"http-status-code.mdx",
"start-server.mdx",
"create-handler.mdx",
"get-server-function-meta.mdx"
"get-server-function-meta.mdx",
"create-middleware.mdx"
]
}
}
Loading