Nest

How can we fix hydration mismatches when mixing legacy Express middleware with new NestJS v11 boilerplates?

March 18, 2026

download ready
Thank You
Your submission has been received.
We will be in touch and contact you soon!

Use NestJS interceptors instead of legacy Express middleware that directly modifies the response to avoid hydration mismatches in SSR.

Rewrite the legacy middleware as an interceptor that modifies the request or response safely within NestJS’s lifecycle, ensuring proper flow and avoiding breaks in rendering.

Code

import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';

@Injectable()
export class UserContextInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const req = context.switchToHttp().getRequest();
    req.user = getUserFromReq(req);  // Instead of modifying res.locals

    return next.handle();
  }
}

// Apply globally in main.ts
app.useGlobalInterceptors(new UserContextInterceptor());
      
Hire Now!

Need Help with Nest Development ?

Work with our skilled nest developers to accelerate your project and boost its performance.
**Hire now**Hire Now**Hire Now**Hire now**Hire now

How can we fix hydration mismatches when mixing legacy Express middleware with new NestJS v11 boilerplates?

Use NestJS interceptors instead of legacy Express middleware that directly modifies the response to avoid hydration mismatches in SSR.

Rewrite the legacy middleware as an interceptor that modifies the request or response safely within NestJS’s lifecycle, ensuring proper flow and avoiding breaks in rendering.

Code

import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';

@Injectable()
export class UserContextInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const req = context.switchToHttp().getRequest();
    req.user = getUserFromReq(req);  // Instead of modifying res.locals

    return next.handle();
  }
}

// Apply globally in main.ts
app.useGlobalInterceptors(new UserContextInterceptor());