typescript 31 lines · 6 steps

How middleware binds to routes in NestJS

A NestJS module implements NestModule to apply, exclude, and target middleware on specific routes.

Explained by highlit
1import {
2 MiddlewareConsumer,
3 Module,
4 NestModule,
5 RequestMethod,
6} from '@nestjs/common';
7import { LoggerMiddleware } from './common/middleware/logger.middleware';
8import { CorrelationIdMiddleware } from './common/middleware/correlation-id.middleware';
9import { UsersController } from './users/users.controller';
10import { UsersModule } from './users/users.module';
11import { AuthModule } from './auth/auth.module';
12 
13@Module({
14 imports: [UsersModule, AuthModule],
15})
16export class AppModule implements NestModule {
17 configure(consumer: MiddlewareConsumer) {
18 consumer
19 .apply(CorrelationIdMiddleware, LoggerMiddleware)
20 .exclude(
21 { path: 'auth/login', method: RequestMethod.POST },
22 { path: 'auth/refresh', method: RequestMethod.POST },
23 'health/(.*)',
24 )
25 .forRoutes(
26 { path: 'users', method: RequestMethod.GET },
27 { path: 'users/*', method: RequestMethod.ALL },
28 UsersController,
29 );
30 }
31}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Middleware is wired declaratively in configure(), not registered globally in a bootstrap file.
  2. 2exclude() and forRoutes() let you scope middleware precisely by path and HTTP method.
  3. 3Multiple middleware passed to apply() run in the order they are listed.

Related explainers

typescript
import { registerLocaleData } from '@angular/common';
import localeFr from '@angular/common/locales/fr';
import localeFrExtra from '@angular/common/locales/extra/fr';
import localeDe from '@angular/common/locales/de';

Locale-aware bootstrapping in Angular

i18n localization dependency-injection
Intermediate 8 steps
typescript
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import * as Joi from 'joi';
 

Validating env config at boot in NestJS

configuration schema-validation environment-variables
Intermediate 8 steps
java
@Component
@Converter
public class EncryptedStringConverter implements AttributeConverter<String, String> {
 

Transparent column encryption in Spring & JPA

encryption aes-gcm jpa-converter
Advanced 10 steps
python
import time
import uuid
 
from django.utils.deprecation import MiddlewareMixin

Attaching per-request context in Django

middleware request lifecycle multi-tenancy
Intermediate 7 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Cache } from 'cache-manager';
import { InjectRepository } from '@nestjs/typeorm';

A cache-aside country lookup in NestJS

cache-aside dependency-injection batch-lookup
Intermediate 8 steps
java
package com.acme.billing.config;
 
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;

Feature-flagged beans with Spring @ConditionalOnProperty

feature-flags conditional-beans strategy-pattern
Intermediate 5 steps

Share this explainer

Here's the card — post it anywhere.

How middleware binds to routes in NestJS — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code