Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

573
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda