Nest
Nest

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

March 18, 2026

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 ?

Ready to leverage the power of conversational AI? Start your project with Zignuts expert AI developers.
bg-image
download-image
Company Deck
PDF, 3MB
© 2026 Zignuts Technolab. All Rights Reserved.
branch imagesbranch imagesbranch imagesbranch imagesbranch imagesbranch images