Middlewares

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.ts

In this example:

  • The middleware hello/middleware.ts runs before /hello and /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.ts

In this example:

  • The middleware hello/middleware.ts runs before the routes /hello and /hello/world.
  • The middleware hello/world/middleware.ts runs only before the route /hello/world.

Using middlewares with Collections

> api
  > hello
    + route.ts
  > (gated)
    + middleware.ts
    + route.ts
    > hello
      > world
        + route.ts

In this example:

  • The middleware (gated)/middleware.ts runs before the routes / and /hello/world
  • The middleware is not applied to the route /hello which lives outside the (gated) collection.