Skip to content
NestPath

Middleware

Position zero of the pipeline. Request-ID correlation logging, rate limiting, helmet, CORS, the MiddlewareConsumer API, and the definitive middleware-vs-guard decision matrix.

Alright, let's talk about Middleware — the bouncer standing outside the building before anyone even reaches the lobby. You've built guards, interceptors, pipes, and filters. Middleware is the layer that runs before all of them, and if you're coming from Express/Next.js, this is the one concept you already know — just with a NestJS wrapper around it.

Analogy

Think of your API as an office building. Middleware is everything at the street entrance — the sign-in desk, the metal detector, the visitor counter — that every visitor passes through before anyone upstairs even knows they exist. The offices (your controllers) never see a visitor the entrance has already turned away.


Why Middleware When You Already Have Guards and Interceptors?

Fair question. You've got guards for auth, interceptors for response wrapping, pipes for validation. Why do you need another layer?

Here's the distinction that matters:

Middleware operates on the raw HTTP request/response. It doesn't know about NestJS. It doesn't know which controller will handle the request. It doesn't have access to ExecutionContext. It can't read @Roles() or @Public() decorators. It's pure Express middleware — req, res, next.

Guards/Interceptors/Pipes operate within NestJS's execution context. They know the controller, the handler, the metadata, the decorators.

So middleware is for things that are framework-agnostic and need to happen before NestJS even starts routing:

  • Request logging (raw HTTP level, before NestJS touches it)
  • CORS handling
  • Rate limiting
  • Request ID generation
  • Body parsing
  • Helmet (security headers)
  • IP whitelisting
  • Request/response compression

If your logic needs to know which route is being hit or what decorators are on the handler → use a Guard or Interceptor.

If your logic just needs the raw request object and doesn't care about NestJS specifics → Middleware.

Analogy

The lobby staff do not know which office you are visiting or what your appointment says — they run the checks that apply to every human who walks in the door. The receptionist on the fifth floor (a guard) is the one who knows whose calendar you are on. If a rule applies to every visitor regardless of destination, it belongs in the lobby; if it depends on who you are meeting, it belongs upstairs.


Where Middleware Sits — For the Last Time, the Full Picture

Incoming HTTP Request
1
MIDDLEWARE — you are here

raw req/res/next — Express-compatible. Runs before route resolution.

2
GUARDS
3
INTERCEPTORS (pre)
4
PIPES
5
CONTROLLER
6
SERVICE
7
INTERCEPTORS (post)
HTTP Response (or Exception Filter if error)

Middleware is position zero. The first code that touches your request. If middleware says no, nothing else runs — not guards, not interceptors, not your controller. Nothing.

Analogy

If the revolving door at street level refuses to turn, it does not matter how friendly the ninth-floor receptionist is — nobody ever meets her. Position zero means the lobby decides first, and every layer above only ever sees visitors who made it through.


Two Ways to Create Middleware

NestJS supports two styles. Understand both.

Style 1: Class Middleware (NestJS way — supports DI)

Implements NestMiddleware, has access to dependency injection.

ts
@Injectable()
export class SomeMiddleware implements NestMiddleware {
  constructor(private someService: SomeService) {} // DI works

  use(req: Request, res: Response, next: NextFunction) {
    // do stuff
    next();
  }
}

Style 2: Functional Middleware (Express way — simpler, no DI)

Just a function. Identical to Express middleware. Use when you don't need DI.

ts
export function someMiddleware(req: Request, res: Response, next: NextFunction) {
  // do stuff
  next();
}

When to use which? If your middleware needs to inject a service (ConfigService, LoggerService, a database connection) → class middleware. If it's self-contained logic → functional middleware. Most middleware you write will be functional because middleware should be thin.

Analogy

Class middleware is a staffed sign-in desk — the clerk has a phone line to other departments (dependency injection) when a check needs help. Functional middleware is the automatic turnstile: self-contained, no phone, one job. Most lobby equipment should be turnstiles, not staffed desks.


Middleware 1: Request Logger — Correlation and Tracing

"Wait, you already have a LoggingInterceptor. Why another logger?"

Because the interceptor runs after guards. If a guard rejects the request, your interceptor never logs it. You have zero visibility into rejected requests. In production, you need to know about every request — especially the ones that fail at the gate.

Also, this middleware adds a request ID — a unique identifier attached to every request that flows through your entire pipeline. When something breaks at 3 AM and you're reading logs, correlation IDs are the difference between finding the bug in 5 minutes vs 5 hours.

Analogy

The lobby sign-in book records everyone who enters the building — including the people security later turns away upstairs. Each visitor also gets a numbered badge (the request ID), so when something goes missing on the ninth floor at 3 AM, you can trace exactly which visitor was where, and when.

src/common/middleware/request-logger.middleware.ts

ts
import { Injectable, NestMiddleware, Logger } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import { randomUUID } from 'crypto';

@Injectable()
export class RequestLoggerMiddleware implements NestMiddleware {
  private readonly logger = new Logger('RequestLogger');

  use(req: Request, res: Response, next: NextFunction) {
    // ① Generate unique request ID
    const requestId = req.headers['x-request-id'] as string || randomUUID();

    // Attach to request for downstream access (guards, interceptors, controllers)
    req['requestId'] = requestId;

    // Also set it as response header so client can reference it in bug reports
    res.setHeader('x-request-id', requestId);

    // ② Capture request details
    const { method, originalUrl, ip } = req;
    const userAgent = req.get('user-agent') || 'unknown';
    const startTime = Date.now();

    // ③ Log when response finishes (not when request arrives)
    // res.on('finish') fires after the ENTIRE pipeline completes
    res.on('finish', () => {
      const { statusCode } = res;
      const duration = Date.now() - startTime;

      const logMessage =
        `[${requestId}] ${method} ${originalUrl} → ${statusCode} (${duration}ms) - ${ip} - ${userAgent}`;

      if (statusCode >= 500) {
        this.logger.error(logMessage);
      } else if (statusCode >= 400) {
        this.logger.warn(logMessage);
      } else {
        this.logger.log(logMessage);
      }
    });

    next();
  }
}

Breaking this down:

x-request-id header — If the client (or an API gateway like nginx, AWS ALB) already sends a request ID, we use that. Otherwise, we generate one. This maintains traceability across microservices. Your React frontend can attach a request ID, and you can trace it through every service it hits.

req['requestId'] — Attached to the request object so everything downstream can access it. Your guards, interceptors, exception filters — they all have access to req and can include this ID in their logs.

res.on('finish') — This is an Express/Node event. It fires when the response has been sent to the client. By logging here instead of when the request arrives, we capture the complete picture — status code, total duration including all middleware, guards, interceptors, controller, service, and serialization time. Your interceptor only measures controller+service time. This measures everything.

Log level by status code — 5xx errors go to error (these are your bugs, they should trigger alerts). 4xx goes to warn (client mistakes, worth monitoring for abuse but not emergencies). 2xx/3xx go to log (normal traffic).

Thread the request ID into every response

Right now the request ID lives in your logs and in the x-request-id response header — but not in the response body. Put it in the envelope too, and a user can copy the exact requestId from a failed API response into a bug report, and you can jump straight to that one request in your logs. This is the single most useful piece of production plumbing you'll add.

The middleware already attached req['requestId']. Every downstream layer can read it — so pull it into both the success envelope (your TransformInterceptor from Module 04) and the error envelope (your AllExceptionsFilter from Module 03):

ts
// TransformInterceptor — success envelope
return next.handle().pipe(
  map((data) => ({
    success: true as const,
    data,
    requestId: request['requestId'],   // ← add this
    timestamp: new Date().toISOString(),
    path: request.url,
  })),
);

// AllExceptionsFilter — error envelope
const errorResponse: ErrorResponse = {
  success: false,
  statusCode: status,
  error: this.getErrorName(status),
  message,
  ...(details && { details }),
  requestId: request['requestId'],     // ← add this
  timestamp: new Date().toISOString(),
  path: request.url,
};

Add requestId: string to both the ApiResponse and ErrorResponse interfaces so the shape stays typed. Now every response your API emits — success or error — carries the same ID that's in the logs and the x-request-id header. One request, one ID, visible everywhere. The capstone's envelope requires exactly this.

Analogy

The numbered badge from the sign-in desk isn't just filed in the logbook — it's printed on the visitor's own copy of the paperwork. When they later call to complain about floor nine, they read you the badge number and you find their entire trail in seconds, instead of asking "roughly what time did you come in?"


Middleware 2: CORS Configuration

You know CORS. You've fought it in Next.js. In NestJS, it's typically handled via main.ts, but understanding it as middleware matters:

main.ts — The simple way

ts
async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  app.enableCors({
    origin: ['http://localhost:3001', 'https://yourfrontend.com'],
    methods: ['GET', 'POST', 'PATCH', 'DELETE'],
    allowedHeaders: ['Content-Type', 'Authorization'],
    credentials: true,
  });

  // ... pipes, filters, interceptors
  await app.listen(3000);
}

This is Express's cors middleware under the hood. NestJS wraps it for convenience. For most apps, this is all you need. But if you need dynamic CORS (different origins for different routes), you'd write a custom middleware.

Analogy

CORS is the building's guest policy: a posted list of partner companies whose employees are welcome. When a browser from another origin knocks, the lobby checks the list before the request gets anywhere near an office.


Middleware 3: Helmet — Security Headers

If you're deploying an API without security headers, you're handing attackers free ammunition.

bash
npm install helmet

main.ts

ts
import helmet from 'helmet';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  app.use(helmet()); // ← Express middleware, applied directly

  // ... rest of setup
}

helmet() sets headers like X-Content-Type-Options: nosniff, Strict-Transport-Security, X-Frame-Options, etc. It's a functional middleware — no NestJS wrapper needed. app.use() accepts any Express-compatible middleware.

Analogy

Helmet is the standard safety kit bolted to the entrance — metal detector, reinforced glass, fire doors — installed once and applied to everyone. You do not armor each office individually; you harden the front door and every visitor passes through the same protections.

This is when to use app.use() vs module-based registration: third-party Express middleware that doesn't need NestJS features goes directly in main.ts via app.use().


Middleware 4: Rate Limiter — Prevent Abuse

Without rate limiting, someone can hammer your POST /tasks endpoint 10,000 times per second and fill your in-memory array until the process crashes. Or worse, in production with a real DB — they run up your cloud bill.

Functional middleware approach (simplified, for understanding):

src/common/middleware/rate-limiter.middleware.ts

ts
import { Request, Response, NextFunction } from 'express';

// In-memory store — in production use Redis
const requestCounts = new Map<string, { count: number; resetTime: number }>();

const WINDOW_MS = 60 * 1000; // 1 minute
const MAX_REQUESTS = 100;    // 100 requests per minute per IP

export function rateLimiterMiddleware(
  req: Request,
  res: Response,
  next: NextFunction,
) {
  const clientIp = req.ip || req.socket.remoteAddress || 'unknown';
  const now = Date.now();

  const record = requestCounts.get(clientIp);

  if (!record || now > record.resetTime) {
    // first request or window expired — start fresh
    requestCounts.set(clientIp, { count: 1, resetTime: now + WINDOW_MS });
    next();
    return;
  }

  record.count++;

  if (record.count > MAX_REQUESTS) {
    res.status(429).json({
      success: false,
      statusCode: 429,
      error: 'Too Many Requests',
      message: `Rate limit exceeded. Try again in ${Math.ceil((record.resetTime - now) / 1000)}s`,
      timestamp: new Date().toISOString(),
      path: req.originalUrl,
    });
    return; // don't call next() — request stops here
  }

  next();
}

Why this is middleware and not a guard:

Rate limiting doesn't care about your route, your decorators, your controller, or your NestJS context. It cares about IP address and request count. Pure HTTP-level concern. It should stop abuse before NestJS even starts processing the request. If this were a guard, NestJS would still parse the body, resolve the route, and do work before rejecting. Wasted computation.

Analogy

The visitor cap is enforced on the sidewalk: once a company has sent a hundred people this hour, the next one never even reaches the turnstile. Letting them ride the elevator up just so a receptionist can turn them away would waste the whole building's time — which is exactly why this check happens at position zero and not in a guard.

Production note: Use @nestjs/throttler instead of rolling your own. It integrates with NestJS's module system and supports Redis stores. But understanding the raw version first means you'll know what that package is doing under the hood.


Registering Middleware — The Module configure() Method

Unlike guards, interceptors, and filters which use APP_* tokens or app.useGlobal*(), NestJS class middleware is registered through the module's configure method.

app.module.ts — Updated

ts
import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { APP_GUARD } from '@nestjs/core';
import { TasksModule } from './tasks/tasks.module';
import { AuthGuard } from './common/guards/auth.guard';
import { RolesGuard } from './common/guards/roles.guard';
import { RequestLoggerMiddleware } from './common/middleware/request-logger.middleware';
import { rateLimiterMiddleware } from './common/middleware/rate-limiter.middleware';

@Module({
  imports: [TasksModule],
  providers: [
    {
      provide: APP_GUARD,
      useClass: AuthGuard,
    },
    {
      provide: APP_GUARD,
      useClass: RolesGuard,
    },
  ],
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    // Class middleware — applied to all routes
    consumer
      .apply(RequestLoggerMiddleware)
      .forRoutes('*');

    // Functional middleware — applied to all routes
    consumer
      .apply(rateLimiterMiddleware)
      .forRoutes('*');
  }
}

NestJS 11 / Express 5 changed the wildcard syntax

On NestJS 11+ (which ships Express 5 and path-to-regexp v8), a bare .forRoutes('*') throws TypeError: Missing parameter name. Named wildcards are now required:

ts
// NestJS 10 and earlier
consumer.apply(RequestLoggerMiddleware).forRoutes('*');

// NestJS 11+ (Express 5) — name the wildcard
consumer.apply(RequestLoggerMiddleware).forRoutes('{*path}');
// or target everything the framework-native way:
consumer.apply(RequestLoggerMiddleware).forRoutes({ path: '*path', method: RequestMethod.ALL });

The examples below use '*' for readability — if you're on Nest 11, swap in '{*path}'. The same applies to any @Get('*') catch-all routes.

MiddlewareConsumer — The route configuration API:

ts
// Apply to everything
consumer.apply(SomeMiddleware).forRoutes('*');

// Apply to specific path
consumer.apply(SomeMiddleware).forRoutes('tasks');

// Apply to specific method + path
consumer.apply(SomeMiddleware).forRoutes(
  { path: 'tasks', method: RequestMethod.POST },
  { path: 'tasks', method: RequestMethod.DELETE },
);

// Apply to a controller class
consumer.apply(SomeMiddleware).forRoutes(TasksController);

// Exclude specific routes
consumer
  .apply(SomeMiddleware)
  .exclude(
    { path: 'health', method: RequestMethod.GET },
    { path: 'tasks', method: RequestMethod.GET },
  )
  .forRoutes('*');

// Chain multiple middleware (execution order = apply order)
consumer
  .apply(FirstMiddleware, SecondMiddleware, ThirdMiddleware)
  .forRoutes('*');

vs app.use() in main.ts:

ts
// main.ts — global, no route filtering, Express-style
app.use(helmet());                    // all routes, no exceptions
app.use(rateLimiterMiddleware);       // all routes, no exceptions

// Module configure() — NestJS-style, route filtering, DI support
consumer.apply(RequestLoggerMiddleware)
  .exclude({ path: 'health', method: RequestMethod.GET })
  .forRoutes('*');

Rule of thumb: Third-party Express middleware that applies to everything → app.use() in main.ts. Custom middleware that needs route filtering or DI → module configure().

Analogy

Off-the-shelf equipment that protects the entire building — turnstiles, metal detectors — gets bolted straight onto the front entrance for everyone. Custom procedures that apply only to certain wings, or that need a clerk with a phone line, get written into the building's own operations manual instead.


Updated main.ts — The Clean Version

ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';
import { AllExceptionsFilter } from './common/filters/all-exceptions.filter';
import { TransformInterceptor } from './common/interceptors/transform.interceptor';
import { LoggingInterceptor } from './common/interceptors/logging.interceptor';
import { TimeoutInterceptor } from './common/interceptors/timeout.interceptor';
import helmet from 'helmet';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  // ① Express-level middleware (runs first, no NestJS context)
  app.use(helmet());
  app.enableCors({
    origin: ['http://localhost:3001'],
    credentials: true,
  });

  // ② Global pipes (validation)
  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,
      forbidNonWhitelisted: true,
      transform: true,
    }),
  );

  // ③ Global filters (error formatting)
  app.useGlobalFilters(new AllExceptionsFilter());

  // ④ Global interceptors (response wrapping, logging, timeout)
  app.useGlobalInterceptors(
    new LoggingInterceptor(),
    new TransformInterceptor(),
    new TimeoutInterceptor(),
  );

  // Guards registered via APP_GUARD in AppModule (DI-aware)

  // NestJS middleware registered via configure() in AppModule

  await app.listen(3000);
}
bootstrap();

Let's Trace a Full Request — Every Layer Active

POST /tasks with Authorization: Bearer valid-user-token and body { "title": "Full trace", "description": "every layer" }

HTTP Request arrives at server
1
HELMET MIDDLEWARE (main.ts — app.use)

→ sets security headers on response
→ calls next()

2
CORS MIDDLEWARE (main.ts — enableCors)

→ checks origin, sets Access-Control-* headers
→ calls next()

3
REQUEST LOGGER MIDDLEWARE (module configure)

→ generates requestId: "a1b2c3d4-..."
→ attaches to req and response header
→ registers res.on('finish') callback
→ calls next()

4
RATE LIMITER MIDDLEWARE (module configure)

→ checks IP: 192.168.1.1 → 15 requests this window → under 100 limit
→ calls next()

5
AUTH GUARD

→ not @Public() on create()
→ extracts Bearer token → "valid-user-token"
→ validates → user = { id:1, username:'testuser', roles:['user'] }
→ attaches to request → return true

6
ROLES GUARD

→ no @Roles() on create() → no restriction → return true

7
LOGGING INTERCEPTOR (pre)

→ logs "→ POST /tasks"
→ starts timer

8
TRANSFORM INTERCEPTOR (pre)

→ nothing to do before controller

9
TIMEOUT INTERCEPTOR
→ starts 5s countdown
10
VALIDATION PIPE

→ transforms body → CreateTaskDto instance
→ validates: @IsString() ✓, @IsNotEmpty() ✓, @MaxLength(100) ✓
→ passes validated DTO to controller

11
CONTROLLER (TasksController.create)

→ receives validated DTO + @CurrentUser('username') = 'testuser'
→ calls tasksService.create(dto)

12
SERVICE (TasksService.create)

→ creates task { id:1, title:'Full trace', description:'every layer', done:false }
→ returns task

13
TIMEOUT INTERCEPTOR (post)

→ completed in 3ms, well under 5s → no timeout

14
TRANSFORM INTERCEPTOR (post)

→ wraps: { success:true, data:{...task}, timestamp:'...', path:'/tasks' }

15
LOGGING INTERCEPTOR (post)

→ logs "← POST /tasks [5ms]"

16
RESPONSE SENT TO CLIENT

→ status 201
→ headers include x-request-id, security headers, CORS headers
→ body: { success:true, data:{...}, timestamp, path }

17
REQUEST LOGGER res.on('finish') callback fires

→ logs [a1b2c3d4] POST /tasks → 201 (5ms) - 192.168.1.1 - PostmanRuntime/7.x

⚡ Quick lookup — all 17 steps in one glance
text
1 Helmet -> 2 CORS -> 3 Request Logger -> 4 Rate Limiter        (middleware)
-> 5 AuthGuard -> 6 RolesGuard                                  (guards)
-> 7 Logging -> 8 Transform -> 9 Timeout                        (interceptors pre)
-> 10 ValidationPipe -> 11 Controller -> 12 Service
-> 13 Timeout -> 14 Transform -> 15 Logging                     (interceptors post)
-> 16 Response sent -> 17 Request Logger finish callback

17 steps. Every single layer you've built, firing in order. And your controller is still 3 lines of code calling a service. That's the architecture working.

Analogy

Follow one visitor from the sidewalk to a ninth-floor meeting: through the scanners, past the sign-in desk, cleared by two receptionists, into the meeting, and back out with a stamped exit slip. Seventeen checkpoints fired, and the person they came to see only had to do their actual job.


When Middleware Gets Skipped — The Error Path

DELETE /tasks/1 with no token:

① Helmet → ② CORS → ③ Request Logger → ④ Rate Limiter
5
AUTH GUARD

→ not @Public(), no token
→ throw UnauthorizedException

SKIPPED: RolesGuard, Interceptors, Pipes, Controller, Service
6
EXCEPTION FILTER

→ formats: { success:false, statusCode:401, message:'No token provided', ... }

7
RESPONSE SENT (401)
8
REQUEST LOGGER res.on('finish')

→ logs [x1y2z3] DELETE /tasks/1 → 401 (1ms) - 192.168.1.1

Notice — the request logger still captures the failed request because res.on('finish') fires regardless of success or failure. That's why we put logging at the middleware level. If it were only in the interceptor, this 401 request would be invisible.

Analogy

Even when security turns a visitor away on the fifth floor, the lobby's sign-in book still shows when they entered and when they left. That is exactly why the logbook lives at the entrance and not inside any one office — it sees everyone, including the rejected.


Middleware vs Guard vs Interceptor — Decision Matrix

QuestionUse
Does it need req/res/next only, no NestJS context?Middleware
Does it need to know which controller/method handles the request?Guard or Interceptor
Should this request be allowed to proceed? (yes/no decision)Guard
Should the response be transformed/wrapped?Interceptor
Should the input data be validated/transformed?Pipe
Should errors be formatted?Exception Filter
Is it third-party Express middleware (helmet, cors, compression)?app.use() in main.ts
Does it need DI and route-level configuration?Class middleware in module
Is it a simple function with no dependencies?Functional middleware

If you can't decide, ask: "Does this logic care about NestJS decorators and metadata?" If no → middleware. If yes → guard/interceptor.

Analogy

Ask where the check would physically happen: lobby staff handle anything that is true for every visitor no matter their destination, while floor receptionists handle anything that depends on who is being visited. If the check needs to read the appointment book (NestJS metadata), it cannot happen at the front door.


Updated Project Structure

src
app.module.ts
main.ts
common
decorators
public.decorator.ts
roles.decorator.ts
current-user.decorator.ts
filters
all-exceptions.filter.ts
guards
auth.guard.ts
roles.guard.ts
interceptors
transform.interceptor.ts
logging.interceptor.ts
timeout.interceptor.ts
middleware
request-logger.middleware.ts
rate-limiter.middleware.ts
interfaces
api-response.interface.ts
error-response.interface.ts
exceptions
task-not-found.exception.ts
tasks
tasks.module.ts
tasks.controller.ts
tasks.service.ts
dto
create-task.dto.ts
update-task.dto.ts
interfaces
task.interface.ts

What You've Built — The Complete NestJS Backend Architecture

Every layer of the NestJS request lifecycle is now implemented in your CRUD app:

text
Middleware    → request ID, logging, rate limiting, security headers, CORS
Guards       → JWT authentication, role-based authorization
Interceptors → response wrapping, timing, timeout protection
Pipes        → DTO validation, type transformation
Controllers  → thin route handlers with clean decorators
Services     → business logic, data access
Filters      → consistent error formatting, crash protection

You started with a naked CRUD and systematically added every architectural layer NestJS offers, understanding not just what each does, but why it exists at that specific position in the pipeline.


From here, the practical next steps for production readiness: database integration (TypeORM or Prisma with NestJS modules), real JWT auth with login/register/refresh tokens, or testing (unit + e2e with NestJS's built-in testing utilities). Which direction do you want to go?