Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

581
Views
Nestjs Error: Cannot set headers after they are sent to the client

I have a global middleware and a global guard, when request goes into the guard it apparently sends a response(the request doesn't get to the controllers), which is strange because the client gets 404, and nestjs throws an error "Cannot set headers after they are sent to the client". If I disable the middleware everything works fine. How can i fix this?

Middleware:

@Injectable()
export class AuthMiddleware implements NestMiddleware {
  @Inject()
  private readonly usersService: UsersService;
  @Inject()
  private readonly tokenService: TokenService;



  async use(req: Request, res: Response, next: NextFunction): Promise<void> {
    if (!req.cookies.token) {
      req.user = {
        userId: null,
        personId: null,
        role: null,
      };

      next();
    }

    try {
      const result = this.tokenService.verifyToken(req.cookies.token);
      const user = await this.usersService.findOne(result.userId);

      if (!user) {
        req.user = {
          userId: null,
          personId: null,
          role: null,
        };

        next();
      }

      req.user = {
        userId: result.userId,
        personId: result.personId,
        role: result.role,
      };
    } catch {
      req.user = {
        userId: null,
        personId: null,
        role: null,
      };
    }

    next();
  }
}

Guard:

@Injectable()
export class RoleGuard implements CanActivate {
  constructor(private reflector: Reflector) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const req: Request = await context.switchToHttp().getRequest();

    const requiredRole = this.reflector.get<Roles | null>(
      'requiredRole',
      context.getHandler(),
    );

    if (!requiredRole) {
      return true; // everything breaks here
    }

    if (
      requiredRole !== req.body.user.role &&
      req.body.user.role !== Roles.ADMIN
    ) {
      return false;
    }

    return true;
  }
}

main.ts:

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.use(cookieParser());
  app.use(urlencoded({ extended: true }));
  app.useGlobalPipes(
    new ValidationPipe({
      transform: true,
    }),
  );
  app.useGlobalGuards(new RoleGuard(new Reflector()));

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

app.module.ts:

@Module({
  imports: [
    ConfigModule.forRoot({
      envFilePath: '.env',
    }),
    TypeOrmModule.forRoot(getOrmConfig()),
    UserModule,
    EventModule,
  ],
  controllers: [],
  providers: [RoleGuard],
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(AuthMiddleware).forRoutes({
      path: '*',
      method: RequestMethod.ALL,
    });
  }
}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Somehow I managed to fix it by deleting this from AuthGuard:

if (!req.cookies.token) {
    req.user = {
    userId: null,
    personId: null,
    role: null,
  };

  next();
}

Maybe someone knows why it worked?

about 4 years ago · Juan Pablo Isaza Report

0

I suppose it happens due to inappropriate next() function call implementation.

The error you are getting is because after calling next(), you have some additional code to run which will call next() which will cause your controller to send a response back to the client, but it was already sent by your first call.

To fix current realisation simple change next() - > to return next() here more info about it

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!