Issue with NestJS verification of AWS Cognito JWT: "Error: applicationRef.isHeadersSent function not recognized"

I have integrated AWS Cognito as the authentication service for my NestJS application. However, when accessing the endpoint without a JWT (unauthenticated), the server crashes and displays the error

TypeError: applicationRef.isHeadersSent is not a function
. Strangely enough, everything functions correctly when a valid JWT is provided, resulting in the correct data being returned by the API Endpoint protected by the auth guard. Here is the setup I used for the authentication configuration and auth guard. Could someone please review this? Thank you in advance!

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

{
  "name": "moment-share-service",
  "version": "0.0.1",
  "description": "",
  "author": "",
  [...]

Stack Trace

        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)
    [...]

result of 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
[...]

Answer №1

Ensure consistency in the major versions of all NestJS related packages; for instance, the following combination caused an issue:

"@nestjs/core": "^9.4.2"`
"@nestjs/platform-express": "^8.0.0",

In your situation, opt for either 9.*.* or 8.*.*:

[Nest CLI]
Nest CLI Version : 8.2.8 

[Nest Platform Information]
platform-express version : 8.4.7  <----- 8.*.*
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  <----- 9.*.*
config version           : 2.3.1
core version             : 9.4.0  <----- 9.*.*
cli version              : 8.2.8

Answer №2

During my troubleshooting process, I came across an error while utilizing exception filters.

@Catch()
export class PrismaExceptionFilter extends BaseExceptionFilter {
    catch(exception: PrismaClientKnownRequestError, host: ArgumentsHost) {

        // The error stemmed from this particular method call
        super.catch(exception, host);

        // Additional sections of code
    }
}

Upon inspecting the main.ts file where I had globally registered the filter, I resolved the issue by making the following adjustment:

app.useGlobalFilters(new PrismaExceptionFilter())

This was replaced with:

const { httpAdapter } = app.get(HttpAdapterHost);

app.useGlobalFilters(new PrismaExceptionFilter(httpAdapter))

Answer №3

Consider updating the following function

validate(payload: unknown)

with the revised version:

validate(req: Request, payload: unknown)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for receiving an array input in a GraphQL resolver

My query variables contain an array of strings that I need to use as the ids parameter inside my resolver. Below is the relevant code snippet. People.resolver.ts import { Resolver, Query, Mutation, Args, } from '@nestjs/graphql'; import { Peopl ...

Several values are not equal to the typeorem parameter

I am looking for a way to create a Typeorm query that will return results similar to the following SQL statement: SELECT * FROM Users WHERE id <> 3 and id <> 8 and id <> 23; Any suggestions on how I can achieve this? Thank you! ...

I am attempting to activate the "about us" button on the website. I have successfully included the path and added a router link to the containing div of the button. However, there seems to be something

In my app, the first step involves specifying the path in the routing module. Following that is defining the home component, then the app component, and finally creating the button using HTML. Setting up the path in the app.routing.module.ts file <div ...

Issue with Angular Compilation When Importing Library Function into Web Worker

I am facing an issue with a web worker in Angular that used to function properly in the previous versions: /// <reference lib="webworker" /> import { ParseResult } from "papaparse"; import { readCSV } from '@fireflysemantics/ ...

Distribute among an array of specific types

I am trying to achieve this behavior using Typescript: type animals = 'cat' | 'dog' let selectedAnimals: animals[] = ['cat'] selectedAnimals = [ // <- Type 'string[]' is not assignable to type 'animals[]&ap ...

The Datatable is displaying the message "The table is currently empty" despite the fact that the rows have been loaded through Angular

My experience with displaying a data table in Angular was frustrating. Even though all the records were present in the table, it kept showing "no data available." Additionally, the search function refused to work as intended. Whenever I tried searching for ...

Converting CommonJS default exports into named exports / Unable to load ES module

I've encountered an issue while creating a Discord bot with discord.js using TypeScript. When attempting to run the resulting JavaScript code, I'm facing an error that states: import { Client, FriendlyError, SQLiteProvider } from 'discord.js ...

Avoiding redundant EventEmitters when transferring @Output to a child component

While working on a form component, I decided to separate the form action buttons into a child component. This led me to create two EventEmitter and handlers for the same action. I'm wondering if there is a way to directly pass the 'onDiscard&apo ...

Anticipate that the function parameter will correspond to a key within an object containing variable properties

As I develop a multi-language application, my goal is to create a strict and simple typing system. The code that I am currently using is as follows: //=== Inside my Hook: ===// interface ITranslation { [key:string]:[string, string] } const useTranslato ...

Is there a substitute for useState in a Next.js server component?

With my static site at , the only interactive feature being the dark mode toggle, I understand that using useState is not feasible in a server component. export default function RootLayout({ children }: { children: React.ReactNode }) { const [darkMode, ...

Exploring the potential of TypeScript with native dynamic ES2020 modules, all without the need for Node.js, while also enhancing

I have a TypeScript application that utilizes es16 modules, with most being statically imported. I am now looking to incorporate a (validator) module that is only imported in debug mode. Everything seems to be functioning properly, but I am struggling to f ...

Is there a way in Typescript to filter for the first instance of a unique object in an array of objects?

Having an array of JSON objects like this, the task is to iterate through it and retrieve the first occurrence of 'appname', such as 'app1' or 'app2', and store the entire object for each... myArray[ { ...

Methods for assigning values to a formControl using an array

I have an array of objects and I am attempting to loop through the array, dynamically setting values to a formControl and not displaying anything if the value is null. I have searched for similar solutions but haven't found any references or examples ...

The attribute 'commentText' is not found within the 'Comment' data type

Currently, I am immersed in building a user-friendly social network application using Angular 12 for my personal educational journey. Running into an error has left me puzzled and looking for assistance. About the Application: The home page (home.compone ...

What is the best way to include multiple targets/executables within a single Node.js repository?

My React Native app is developed using TypeScript, and I want to create CLI tools for developers and 'back office' staff also in TypeScript. These tools should be part of the same monorepo. After attempting to do this by creating a subfolder wit ...

Having trouble injecting $resource into my Jasmine unit test

I've encountered an issue while trying to test my self-written service that utilizes $resource. I'm facing difficulties when trying to inject $resource into my test spec. My setup includes Typescript with AngularJS 1.6.x, and here is a snippet o ...

Modify every audio mixer for Windows

Currently working on developing software for Windows using typescript. Looking to modify the audio being played on Windows by utilizing the mixer for individual applications similar to the built-in Windows audio mixer. Came across a plugin called win-audi ...

"Enhancing User Experience with Angular 2: Customizing Component Selection and Sty

I am currently working on an Angular application that fetches a configuration file in .json format. My goal is to dynamically choose components and apply inline styles to them. Below is an example of the structure of the configuration data obtained from a ...

"Unsuccessful API request leads to empty ngFor loop due to ngIf condition not being

I have been struggling to display the fetched data in my Angular 6 project. I have tried using ngIf and ngFor but nothing seems to work. My goal is to show data from movies on the HTML page, but for some reason, the data appears to be empty. Despite tryin ...

Utilize the express library (NodeJS, TypeScript) to send back the results of my function

I am curious about how I can handle the return values of my functions in my replies. In this specific scenario, I am interested in returning any validator errors in my response if they exist. Take a look at my SqlCompanyRepository.ts: async create(compan ...