Search code examples
node.jstypescriptjwtnestjs

Getting 'secretOrPrivateKey must have a value' error in NestJS JWT authentication


I'm encountering an error in my NestJS application when using JWT authentication with the @nestjs/jwt package. The error message I'm receiving is "secretOrPrivateKey must have a value." I have followed the official documentation and made sure to configure the JwtModule with the secret key, but the error persists.

Here's the relevant code in my application:

// auth.module.ts:
import { Module } from '@nestjs/common';
import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';
import { EmailService } from 'src/email/email.service';
import { UserService } from 'src/user/user.service';
import { JwtModule, JwtService } from '@nestjs/jwt';
import { jwtConstants } from './constants';

@Module({
  imports: [
    JwtModule.register({
      global: true,
      secret: jwtConstants.secret,
      secretOrPrivateKey: jwtConstants.secret,
      signOptions: { expiresIn: '60s' },
    })
  ],
  providers: [AuthService, UserService, JwtService, EmailService],
  controllers: [AuthController]
})
export class AuthModule {}

// constants.ts:
export const jwtConstants = {
    secret: process.env.JWT_SECRET
}


//auth.service.ts:
import { ForbiddenException, Injectable } from '@nestjs/common'
import { PrismaService } from 'src/prisma/prisma.service'
import { CheckNewPasswordCode, RquestNewPasswordDto, SignInDto, SignUpDto, UpdatePasswordDto, UpdatePrivilegesDto } from './dto'
import { UserService } from 'src/user/user.service'
import { JwtService } from '@nestjs/jwt'

@Injectable()
export class AuthService {
    constructor(private userService: UserService,
        private jwtService: JwtService) { }

    async signUp(dto: SignUpDto) {
        const user = await this.userService.signUp(dto)
        const payload = { sub: user.email, username: user.name }

        return {
            access_token: await this.jwtService.signAsync(payload),
        }
    }

    async signIn(dto: SignInDto) {
        const user = await this.userService.signIn(dto)
        const payload = { sub: user.email, username: user.name }

        return {
            access_token: await this.jwtService.signAsync(payload),
        }
    }
}

I have also checked the following points:

I confirmed that the JWT_SECRET environment variable is correctly set and accessible within my application. I even printed its value in the AuthModule to verify its retrieval.

I have installed the jsonwebtoken package as a dependency in my project.

Despite these efforts, I'm still encountering the same error. Can someone please help me identify what could be causing this issue and provide guidance on how to resolve it? Any suggestions or insights would be greatly appreciated.

Please let me know if any additional information is needed. Thank you!


Solution

  • // I've changed my providers in auth.module.ts from this
    providers: [AuthService, UserService, EmailService, JwtService]
    // to this
    providers: [AuthService, UserService, EmailService]
    

    According to ChatGPT: The reason that importing JwtService from @nestjs/jwt caused the problem is that when you import the JwtService directly, it creates a new instance of the JwtService instead of using the one provided by the JwtModule. As a result, the JwtModule configuration, including the secret key, was not applied to the manually created JwtService instance.

    By removing the import of JwtService and relying on the JwtModule to provide the JwtService, you ensure that the JwtService is properly configured with the secret key specified in the JwtModule options. This allows your authentication logic to function correctly.