You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NestJS集成AWS Cognito JWT验证报错:applicationRef.isHeadersSent不是函数

问题解决:NestJS + AWS Cognito 未认证访问导致服务器崩溃

问题背景

在NestJS应用中集成AWS Cognito作为认证服务,携带有效JWT访问受AuthGuard('jwt')保护的端点时可正常返回数据,但未携带JWT(未认证)访问时,服务器崩溃并抛出错误:

TypeError: applicationRef.isHeadersSent is not a function

相关代码文件

src/authz/authz.module.ts

import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { passportJwtSecret } from 'jwks-rsa';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super({
      secretOrKeyProvider: passportJwtSecret({
        cache: true,
        rateLimit: true,
        jwksRequestsPerMinute: 5,
        jwksUri: `https://cognito-idp.us-east-1.amazonaws.com/xxxxx/.well-known/jwks.json`,
      }),
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      issuer: 'https://cognito-idp.us-east-1.amazonaws.com/xxxxx',
      algorithms: ['RS256'],
    });
  }

  validate(payload: unknown): unknown {
    return payload;
  }
}

src/authz/jwt.strategy.ts

import { Module } from '@nestjs/common';
import { PassportModule } from '@nestjs/passport';
import { JwtStrategy } from './jwt.strategy';

@Module({
  imports: [PassportModule.register({ defaultStrategy: 'jwt' })],
  providers: [JwtStrategy],
  exports: [PassportModule],
})
export class AuthzModule {}

src/app.module.ts

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { GraphQLModule } from '@nestjs/graphql';
import { MomentModule } from './moment/moment.module';
import { graphqlConfigOptions } from './config/graphql';
import { TypeOrmModule } from '@nestjs/typeorm';
import { typeormConfigOptions } from './config/data-source';
import { CharacterModule } from './character/character.module';
import { AuthzModule } from './authz/authz.module';

@Module({
  imports: [
    GraphQLModule.forRoot(graphqlConfigOptions),
    TypeOrmModule.forRoot(typeormConfigOptions),
    MomentModule,
    CharacterModule,
    AuthzModule,
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

src/app.controller.ts

import { Controller, Get, UseGuards } from '@nestjs/common';
import { AppService } from './app.service';
import { ApiBearerAuth, ApiResponse, ApiTags } from '@nestjs/swagger';
import { AuthGuard } from '@nestjs/passport';

@ApiTags('System')
@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get('health')
  @ApiResponse({ status: 200, type: String })
  getHello(): string {
    return this.appService.getHello();
  }

  @UseGuards(AuthGuard('jwt'))
  @Get('secure-message')
  @ApiResponse({ status: 200, type: String })
  @ApiResponse({ status: 401 })
  @ApiBearerAuth()
  getSecureMessage(): string {
    return this.appService.getSecureMessage();
  }
}

package.json 依赖片段

"dependencies": {
  "@apollo/server": "^4.7.0",
  "@nestjs/apollo": "^11.0.5",
  "@nestjs/common": "^9.4.0",
  "@nestjs/config": "^2.3.1",
  "@nestjs/core": "^9.4.0",
  "@nestjs/graphql": "^11.0.5",
  "@nestjs/mapped-types": "*",
  "@nestjs/passport": "^9.0.3",
  "@nestjs/platform-express": "^8.0.0",
  "@nestjs/swagger": "^6.3.0",
  "@nestjs/typeorm": "^9.0.1",
  // 其他依赖...
}

堆栈跟踪

if (!applicationRef.isHeadersSent(response)) {
                            ^
TypeError: applicationRef.isHeadersSent is not a function
    at ExceptionsHandler.catch (D:\self-study\GitHub Repo\Social Media App Suite\social-media-app-suite\moment-share-service\node_modules\@nestjs\core\exceptions\base-exception-filter.js:27:29)
    at ExceptionsHandler.next (D:\self-study\GitHub Repo\Social Media App Suite\social-media-app-suite\moment-share-service\node_modules\@nestjs\core\exceptions\exceptions-handler.js:16:20)
    at D:\self-study\GitHub Repo\Social Media App Suite\social-media-app-suite\moment-share-service\node_modules\@nestjs\core\router\router-proxy.js:13:35
    at processTicksAndRejections (node:internal/process/task_queues:95:5)

npx nest info 结果

[System Information]
OS Version     : Windows 10
NodeJS Version : v18.14.1
YARN Version    : 1.22.17 

[Nest CLI]
Nest CLI Version : 8.2.8 

[Nest Platform Information]
platform-express version : 8.4.7
mapped-types version     : 1.2.2
schematics version       : 8.0.11
passport version         : 9.0.3
graphql version          : 11.0.5
swagger version          : 6.3.0
typeorm version          : 9.0.1
testing version          : 8.4.7
apollo version           : 11.0.5
common version           : 9.4.0
config version           : 2.3.1
core version             : 9.4.0
cli version              : 8.2.8

原因分析

问题根源是NestJS核心包与平台包版本不兼容:

  • @nestjs/core 使用9.4.0版本(9.x系列)
  • @nestjs/platform-express 使用8.4.7版本(8.x系列)

NestJS要求所有核心模块(core、common、platform-*、testing等)必须保持相同大版本,否则内部API会出现不匹配。isHeadersSent方法在NestJS 9.x的ApplicationRef中存在,但8.x版本未定义,导致异常过滤器处理未认证错误时调用该方法失败,引发服务器崩溃。

解决方案

步骤1:统一NestJS包版本

修改package.json中的@nestjs/platform-express版本,使其与@nestjs/core一致:

"@nestjs/platform-express": "^9.4.0"

同时建议将其他旧版本的NestJS相关包(如@nestjs/testing、@nestjs/cli)也升级到9.x版本,避免后续兼容性问题。

步骤2:重新安装依赖

执行命令更新依赖:

npm install
# 或使用yarn
yarn install

步骤3:验证修复

重启NestJS应用,再次访问未携带JWT的受保护端点,此时应正常返回401 Unauthorized响应,服务器不再崩溃。


内容的提问来源于stack exchange,提问作者Ji Frank

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 23:07:00