Utilizing the configService, the NestJS JwtStrategy is configured to share the secret key

In the example from the NestJS documentation (https://docs.nestjs.com/techniques/authentication), I have the JwtStrategy class:

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
    constructor(
        private readonly authService: AuthService,
        private readonly configService: ConfigService,
    ) {
        super({
            jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
            secretOrKey: this.configService.getSecretKey,
        });
    }
    // ...
}

When attempting to access this before calling super(), an error is encountered. However, it is still desired to utilize the configService for obtaining the secret key.

Although utilizing an environment variable is a viable option, using the service approach seems more clear to me as a solution.

Is there a way to use the configService or retrieve a value from it and pass it to the super() call? Thank you.

Answer №1

To successfully execute the code, simply eliminate this. as demonstrated below:

secretOrKey: configService.getSecretKey

This modification will be effective because the parameter configService has already been passed.

Answer №2

To achieve this in NestJS version 10.0.0, follow these steps:

jwt.strategy.ts

Create a JwtStrategy class that extends PassportStrategy(PassportJwtStrategy) and inject the ConfigService as shown below:
export class JwtStrategy extends PassportStrategy(PassportJwtStrategy) {
  constructor(
    private readonly authService: AuthService,
    @Inject(ConfigService) private readonly configService: ConfigService, // Injected config service here
  ) {
    console.log(`${configService.get('JWT_SECRET')}`);
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: configService.getOrThrow('JWT_SECRET'), // Using config service inside the super constructor
    });
  }
}

app.module.ts

In your AppModule, import UserModule and configure ConfigModule globally by following these settings:
@Module({
  imports: [
    UserModule,
    ConfigModule.forRoot({
      validationSchema: envValidationSchema,
      isGlobal: true, // Register the config module globally
      validationOptions: {
        allowUnknown: true,
        abortEarly: true,
      },
    }),
  ],
  controllers: [],
  providers: [],
})
export class AppModule {}

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

The setter of the computed property is failing to execute

Currently, I am working with a computed property that represents an object of a specific type defined within my Vuex Store. The goal is to utilize this property in my component using v-model. I have thoroughly set up getters and setters for this property a ...

Changing an inline function to a regular function

I am currently attempting to convert the signature of an inline function to a non-inline function: const onMouseEnter = (itemName: string): void => { alert(itemName); }; Despite my efforts, the attempted conversion did not yield the desired outcome. f ...

Looking to determine if two elements exist within an array? Seeking a boolean result based on their presence

Consider the following array of objects: quesListArray = [ { QuestionTypeID : 1, QuestionTypeName : 'Rating' }, { QuestionTypeID : ...

Exploring Typescript Decorators: Extracting the Type of a Property

When working with data from Strapi, I have developed a process of simplifying the flow by converting it using interfaces and then converting it back to its original Strapi format. Essentially, this means taking data in one format and transforming it into a ...

Angular 6 - Build a dynamic single page housing various applications within

I am faced with the task of developing multiple applications using Angular 6. Each application will have its own set of components, services, and more. However, there is also a need for shared services, components, directives, and other elements that will ...

Breaking down the steps to flip between two images when clicked in Vue.js

I'm currently trying to implement a feature in Vue.js where images switch on click. The functionality I'm aiming for is as follows: Upon initial load, the image displays in black, then upon clicking/selecting it, the image transitions into a blu ...

Discovering Type Definitions in Nuxt.js Project Without Manual Imports in VSCode: A Step-by-Step Guide

Having issues with VSCode not recognizing type definitions automatically in a Nuxt.js project with TypeScript. I'm looking to avoid manually importing types in every file. Here's my setup and the problem I'm facing: Configuration My tsconfi ...

What could be causing the Angular error related to this HttpHeader?

Is there anyone who can assist me with why I am encountering an error in my Angular code while trying to use HttpHeaders to read the response status from the backend? Here is the specific error message: https://i.sstatic.net/tQu5t.jpg import { Injectable ...

Having trouble building the React Native app after adding react-native-vector icons?

A recent project I've been working on involved adding react-native-vector-icons using react-native 0.63.4. However, during the build process, I encountered an error when running the command npx react-native run-ios in the terminal. The warnings/errors ...

Using jest-dom without Jest is definitely an interesting challenge that many developers may

Can anyone help me with extending Typescript interfaces? I have come across a situation that I am trying to solve. In my tests, I am utilizing expect without using Jest directly (I installed it separately and it functions properly). Now, I am interested ...

Exploring the new possibilities of Angular 5: Enhanced REST API service with paginated data and object mapping capabilities

After implementing pagination in my REST API backend, I now need to update my Angular services to accommodate the changes. Instead of simply returning an array of objects, the API will now return JSON responses structured like this: { "count": 0, ...

Incorporating an item into an array based on a specific condition

I am looking to dynamically add or remove an object within an array based on a certain condition. The goal is to exclude the object completely if the condition is not met, while leaving the rest of the objects intact. Consider the following scenario: const ...

Getting TypeScript errors when incorporating a variant into a Material-UI button using a custom component

I have created a unique Link component inspired by this particular example. Take a look at the code below: import classNames from 'classnames'; import {forwardRef} from 'react'; import MuiLink, {LinkProps as MuiLinkProps} from '@ma ...

Retrieve Information in a List

I am currently facing an issue while trying to retrieve data from an array. Below is an example of the image array that I am working with. I am specifically looking to get the weather icon data, but unfortunately I encountered this error message: core.js:1 ...

Creating Typescript types from object keys and arrays of string values

I want to create a type based on an Object's keys and values, which are arrays of strings. This type should include all the possible string values like so: const Actions = { foo: ['bar', 'baz'], } # type generated from Actions s ...

What is the method for verifying the types of parameters in a function?

I possess two distinct interfaces interface Vehicle { // data about vehicle } interface Package { // data about package } A component within its props can receive either of them (and potentially more in the future), thus, I formulated a props interface l ...

The React useEffect() hook causing an infinite re-render when trying to fetch all data regardless of

Recently, I've begun diving into React and utilizing the useEffect hook to fetch news and events from a database upon page load. However, when attempting to add a loading spinner, I encountered an unexpected infinite loop issue that has left me scratc ...

Tips on incorporating HTML tags from JSON data into an HTML table cell using Angular 4

Currently working with Angular 4, I have a JSON structure like this: {"Data":[{"View":"<a href="testurl.com">View</a>"]} When trying to bind Data.View("<a href="testurl.com">View</a>") to an HTML <td>, the result in the tabl ...

NestJs Function yielding inconsistent results based on its calling location

There is a puzzling issue that I am unable to solve. I have stored priceHistories in memory within an array. Strangely, when I invoke a get method, the returned value varies depending on where the method is called from. This is the original property and m ...

Universal variable arguments

Is there a way to modify this function that accepts generic rest parameters to also accept an array parameter without using the spread operator? This would make chaining things much clearer: function fn<T>(...args: T[]): Something<T> { } let s ...