Server

createMiddleware

Edit this page

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.

Learn more about middleware in the Middleware documentation.


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

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);
},
});
app.config.ts
import { defineConfig } from "@solidjs/start/config";
export default defineConfig({
middleware: "src/middleware/index.ts",
});
Report an issue with this page