Middlewares
Middlewares allows you to run code before a route is executed. Middlewares can be used to inject data into the route or prevent the route to be executed based on the request parameters.
Convention
Use the file middleware.ts (or .js) inside any subfolder of your api directory to define a middleware. The middleware will apply to all routes in the same folder and any subfolders.
Examples
Basic
> api
> hello
+ middleware.ts
+ route.ts
> world
+ route.tsIn this example:
- The middleware
hello/middleware.tsruns before/helloand/hello/world.
Nested middlewares
You can also nest middlewares. Each middleware applies to its own level and all routes below it.
> api
> hello
+ middleware.ts
+ route.ts
> world
+ middleware.ts
+ route.tsIn this example:
- The middleware
hello/middleware.tsruns before the routes/helloand/hello/world. - The middleware
hello/world/middleware.tsruns only before the route/hello/world.
Using middlewares with Collections
> api
> hello
+ route.ts
> (gated)
+ middleware.ts
+ route.ts
> hello
> world
+ route.tsIn this example:
- The middleware
(gated)/middleware.tsruns before the routes/and/hello/world - The middleware is not applied to the route
/hellowhich lives outside the(gated)collection.