## NestJS lesson 5: 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.

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.

File logger.middleware.ts

import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response } from 'express';

@Injectable()
export class LoggerMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: Function) {
console.log('Request...');
next();
}
}


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.

File: app.module.ts

import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { LoggerMiddleware } from './middleware/logger.middleware';
import { ControllerNameModule } from './controller-name/controller-name.module';

@Module({
imports: [ControllerNameModule],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(LoggerMiddleware)
.forRoutes('controller-name');
}
}

In the above example we have set up the LoggerMiddleware for the /controller-name route handlers that were previously defined inside the ControllerNameModule. 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.

File app.module.ts

import { Module, NestModule, RequestMethod, MiddlewareConsumer } from '@nestjs/common';
import { LoggerMiddleware } from './middleware/logger.middleware';
import { ControllerNameModule } from './controller-name/controller-name.module';

@Module({
imports: [ControllerNameModule],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(LoggerMiddleware)
.forRoutes({ path: 'controller-name', method: RequestMethod.GET });
}
}

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:

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

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:

File app.module.ts:

import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { LoggerMiddleware } from './middleware/logger.middleware';
import { ControllerNameModule } from './controller-name/controller-name.module';
import { ControllerNameController } from './controller-name/controller-name.controller.ts';

@Module({
imports: [ControllerNameModule],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(LoggerMiddleware)
.forRoutes(ControllerNameController);
}
}

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:

consumer
.apply(LoggerMiddleware)
.exclude(
{ path: 'controller-name', method: RequestMethod.GET },
{ path: 'controller-name', method: RequestMethod.POST },
'controller-name/(.*)',
)
.forRoutes(ControllerNameController);

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 ControllerNameController except the three passed to the exclude() method.

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:

File logger.middleware.ts:

import { Request, Response } from 'express';

export function logger(req: Request, res: Response, next: Function) {
console.log(Request...);
next();
};

And use it within the AppModule:

File app.module.ts:

consumer
.apply(logger)
.forRoutes(ControllerNameController);

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:

consumer.apply(cors(), helmet(), logger).forRoutes(ControllerNameController);

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:

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