Rescale logoNEMO

Configuration

Package configuration and explanation

The createMiddleware function is the main entry point for the Next Easy Middlewares package. It allows you to create a middleware helper that can be used to define middleware functions for your Next.js application.

Configuration

This is our basic construction which we will use to create a middleware helper.

middleware.ts
const middlewares = {
  '/api': async ({ response }: MiddlewareFunctionProps) => {
    // middleware functions for /api route
    return response
  },
};
 
const globalMiddlewares = {
  before: async () => {
    // global middleware function that will be executed before any route middleware
  },
  after: async () => {
    // global middleware function that will be executed after any route middleware
  }
}
 
export const middleware = createMiddleware(middlewares, globalMiddlewares);

Path middlewares construction (middlewares)

Type: Record<string, MiddlewareFunction | MiddlewareFunction[]>

This property contains a map of middleware functions that will be executed for specific routes. The key is the route path, and the value is the middleware function.

Let's break down the construction:

Matcher

Type: string (middlewares object key)

In this library is used path-to-regexp package to match the middleware routes path in a same way as Next.js does in config's matcher prop.

middleware.ts
const middlewares = {
  '/api': // middleware functions for /api route
};

This library uses latest version of path-to-regexp due to DoS vulnerability in previous versions that Next.js uses. Please refer to path-to-regexp for current regex support information.

Middleware function

Type: MiddlewareFunction | MiddlewareFunction[]

This is a function that will be executed for the specific route. It can be a single function or an array of functions that will be executed in order.

middleware.ts
const middlewares = {
  '/api': async ({ response }: MiddlewareFunctionProps) => {
    // middleware functions for /api route
    return response
  },
};

Global middlewares construction (globalMiddlewares)

Type: Record<"before" | "after", MiddlewareFunction | MiddlewareFunction[]>

This property contains global middleware functions that will be executed before and after any route middleware.

Before

Type: MiddlewareFunction | MiddlewareFunction[]

This is a global middleware function(s) that will be executed before any route middleware.

After

Type: MiddlewareFunction | MiddlewareFunction[]

This is a global middleware function(s) that will be executed after any route middleware.

middleware.ts
const globalMiddlewares = {
  before: async ({ response }: MiddlewareFunctionProps) => {
    // middleware functions for /api route
    return response
  },
};

Last updated on

On this page