Middleware

Middleware is a function which is called before the route handler. Middleware functions have access to the request and response objects, and the next() middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a variable named next.

Middleware - 图1

Nest middleware are, by default, equivalent to express middleware. The following description from the official express documentation describes the capabilities of middleware:

Middleware functions can perform the following tasks:

  • execute any code.
  • make changes to the request and the response objects.
  • end the request-response cycle.
  • call the next middleware function in the stack.
  • if the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging.

You implement custom Nest middleware in either a function, or in a class with an @Injectable() decorator. The class should implement the NestMiddleware interface, while the function does not have any special requirements. Let’s start by implementing a simple middleware feature using the class method.

logger.middleware.ts

  1. import { Injectable, NestMiddleware } from '@nestjs/common';
  2. import { Request, Response } from 'express';
  3. @Injectable()
  4. export class LoggerMiddleware implements NestMiddleware {
  5. use(req: Request, res: Response, next: Function) {
  6. console.log('Request...');
  7. next();
  8. }
  9. }
  1. import { Injectable } from '@nestjs/common';
  2. @Injectable()
  3. export class LoggerMiddleware {
  4. use(req, res, next) {
  5. console.log('Request...');
  6. next();
  7. }
  8. }

Dependency injection

Nest middleware fully supports Dependency Injection. Just as with providers and controllers, they are able to inject dependencies that are available within the same module. As usual, this is done through the constructor.

Applying middleware

There is no place for middleware in the @Module() decorator. Instead, we set them up using the configure() method of the module class. Modules that include middleware have to implement the NestModule interface. Let’s set up the LoggerMiddleware at the AppModule level.

app.module.ts

  1. import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
  2. import { LoggerMiddleware } from './common/middleware/logger.middleware';
  3. import { CatsModule } from './cats/cats.module';
  4. @Module({
  5. imports: [CatsModule],
  6. })
  7. export class AppModule implements NestModule {
  8. configure(consumer: MiddlewareConsumer) {
  9. consumer
  10. .apply(LoggerMiddleware)
  11. .forRoutes('cats');
  12. }
  13. }
  1. import { Module } from '@nestjs/common';
  2. import { LoggerMiddleware } from './common/middleware/logger.middleware';
  3. import { CatsModule } from './cats/cats.module';
  4. @Module({
  5. imports: [CatsModule],
  6. })
  7. export class AppModule {
  8. configure(consumer) {
  9. consumer
  10. .apply(LoggerMiddleware)
  11. .forRoutes('cats');
  12. }
  13. }

In the above example we have set up the LoggerMiddleware for the /cats route handlers that were previously defined inside the CatsController. We may also further restrict a middleware to a particular request method by passing an object containing the route path and request method to the forRoutes() method when configuring the middleware. In the example below, notice that we import the RequestMethod enum to reference the desired request method type.

app.module.ts

  1. import { Module, NestModule, RequestMethod, MiddlewareConsumer } from '@nestjs/common';
  2. import { LoggerMiddleware } from './common/middleware/logger.middleware';
  3. import { CatsModule } from './cats/cats.module';
  4. @Module({
  5. imports: [CatsModule],
  6. })
  7. export class AppModule implements NestModule {
  8. configure(consumer: MiddlewareConsumer) {
  9. consumer
  10. .apply(LoggerMiddleware)
  11. .forRoutes({ path: 'cats', method: RequestMethod.GET });
  12. }
  13. }
  1. import { Module, RequestMethod } from '@nestjs/common';
  2. import { LoggerMiddleware } from './common/middleware/logger.middleware';
  3. import { CatsModule } from './cats/cats.module';
  4. @Module({
  5. imports: [CatsModule],
  6. })
  7. export class AppModule {
  8. configure(consumer) {
  9. consumer
  10. .apply(LoggerMiddleware)
  11. .forRoutes({ path: 'cats', method: RequestMethod.GET });
  12. }
  13. }

Hint The configure() method can be made asynchronous using async/await (e.g., you can await completion of an asynchronous operation inside the configure() method body).

Route wildcards

Pattern based routes are supported as well. For instance, the asterisk is used as a wildcard, and will match any combination of characters:

  1. forRoutes({ path: 'ab*cd', method: RequestMethod.ALL });

The 'ab*cd' route path will match abcd, ab_cd, abecd, and so on. The characters ?, +, *, and () may be used in a route path, and are subsets of their regular expression counterparts. The hyphen ( -) and the dot (.) are interpreted literally by string-based paths.

Warning The fastify package uses the latest version of the path-to-regexp package, which no longer supports wildcard asterisks *. Instead, you must use parameters (e.g., (.*), :splat*).

Middleware consumer

The MiddlewareConsumer is a helper class. It provides several built-in methods to manage middleware. All of them can be simply chained in the fluent style. The forRoutes() method can take a single string, multiple strings, a RouteInfo object, a controller class and even multiple controller classes. In most cases you’ll probably just pass a list of controllers separated by commas. Below is an example with a single controller:

app.module.ts

  1. import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
  2. import { LoggerMiddleware } from './common/middleware/logger.middleware';
  3. import { CatsModule } from './cats/cats.module';
  4. import { CatsController } from './cats/cats.controller.ts';
  5. @Module({
  6. imports: [CatsModule],
  7. })
  8. export class AppModule implements NestModule {
  9. configure(consumer: MiddlewareConsumer) {
  10. consumer
  11. .apply(LoggerMiddleware)
  12. .forRoutes(CatsController);
  13. }
  14. }
  1. import { Module } from '@nestjs/common';
  2. import { LoggerMiddleware } from './common/middleware/logger.middleware';
  3. import { CatsModule } from './cats/cats.module';
  4. import { CatsController } from './cats/cats.controller.ts';
  5. @Module({
  6. imports: [CatsModule],
  7. })
  8. export class AppModule {
  9. configure(consumer) {
  10. consumer
  11. .apply(LoggerMiddleware)
  12. .forRoutes(CatsController);
  13. }
  14. }

Hint The apply() method may either take a single middleware, or multiple arguments to specify multiple middlewares.

Excluding routes

At times we want to exclude certain routes from having the middleware applied. We can easily exclude certain routes with the exclude() method. This method can take a single string, multiple strings, or a RouteInfo object identifying routes to be excluded, as shown below:

  1. consumer
  2. .apply(LoggerMiddleware)
  3. .exclude(
  4. { path: 'cats', method: RequestMethod.GET },
  5. { path: 'cats', method: RequestMethod.POST },
  6. 'cats/(.*)',
  7. )
  8. .forRoutes(CatsController);

Hint The exclude() method supports wildcard parameters using the path-to-regexp package.

With the example above, LoggerMiddleware will be bound to all routes defined inside CatsControllerexcept the three passed to the exclude() method.

Hoodies, T-shirts, and accessories!

Support our future development by shopping in the official store!

See more

Functional middleware

The LoggerMiddleware class we’ve been using is quite simple. It has no members, no additional methods, and no dependencies. Why can’t we just define it in a simple function instead of a class? In fact, we can. This type of middleware is called functional middleware. Let’s transform the logger middleware from class-based into functional middleware to illustrate the difference:

logger.middleware.ts

  1. export function logger(req, res, next) {
  2. console.log(`Request...`);
  3. next();
  4. };

And use it within the AppModule:

app.module.ts

  1. consumer
  2. .apply(logger)
  3. .forRoutes(CatsController);

Hint Consider using the simpler functional middleware alternative any time your middleware doesn’t need any dependencies.

Multiple middleware

As mentioned above, in order to bind multiple middleware that are executed sequentially, simply provide a comma separated list inside the apply() method:

  1. consumer.apply(cors(), helmet(), logger).forRoutes(CatsController);

Global middleware

If we want to bind middleware to every registered route at once, we can use the use() method that is supplied by the INestApplication instance:

  1. const app = await NestFactory.create(AppModule);
  2. app.use(logger);
  3. await app.listen(3000);