Rescale logoNEMO

Functions

Middleware functions standardization, explanation and usage

This package introduces middleware functions standardization for more elastic approach to development and feature delivery.

Function schema

This example shows all props that are provided for your usage.

_middleware.ts
async ({ request, response, context, event, forward, params }: MiddlewareFunctionProps) => {
  // function body
}

Explanation

Prop:  request

Type: NextRequest

That's a user middleware's request passed to function, which cookies (and only them) can be later updated by forwarded functions in chain.

This props cookies will only deffer from the original user's request if you've forwarded any response it in the chain.

Prop:  response

Type: NextResponse | undefined

This property contains (optional) resposne object that were forwarded in prev middleware function using forward() function.

Forward functions

Learn more about Forward functions in middleware

It can be used for example for checking custom headers from external packages middlewares output that was forwarded in chain.

_middleware.ts
async ({ response }: MiddlewareFunctionProps) => {
  if (response) {
    console.log(response.headers.get('x-custom-header'));
  }
}

If forwarded middleware added any custom headers or cookies, they will be passed to user at the end of the chain no matter if you handled that.

Prop:  context

Type: Map<string, unknown>

This property contains context shared across whole execution chain for every function.

Shared context

Learn more about Shared Context in middleware

If you want to know more about Map interface usage please refer to these docs.

Prop:  event

Type: NextFetchEvent

This property contains event object for serverless functions execution.

It can be used to use Next.js 15 new features like event.waitUntil().

You can read more there: Next.js 15 waitUntil

Prop:  forward

Type: (response: MiddlewareReturn) => void

The forward function allows you to forward the response from one middleware function to another. This can be useful for chaining middleware functions together and creating more complex middleware logic.

Forward functions

Learn more about Forward functions in middleware

Prop:  params

Type: () => Partial<Record<string, string | string[]>>

This property contains route parameters parsed from the URL path. Just like it's working in Next.js pages/routes/layouts but without awaiting.

_middleware.ts
// Example URL: /team/123
// Matcher: '/team/:slug'
 
async ({ params }: MiddlewareFunctionProps) => {
  console.log(params().slug); // Output: 123
}

On this page