Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

585
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda