I was writing an awesome stuff with Express today and I ran into an error, after solving it (thanks to some wonderful geeks on Stackoverflow) I thought it best to write about it just incase anyone runs into this same error in future this article will kind them on how to solve it.
what is the error and why did it occur?
I installed the dotenv dependency with the aim of storing my json web token secret inside it so as to avoid pushing a secret pass to a Github public repo.
Initially, I had put the connection pass of my MongoDB database in it with the name DB_DETAILS and I wanted to add my token secret in the next line. Well, I did just that and boooom! the terminal threw me an error warning at run time.
UnhandledPromiseRejectionWarning: Error: secretOrPrivateKey must have a value
at Object.module.exports as sign
How did I solve this?
You'd be amazed! I only had to replace process.env.TOKEN_SECRET
to ${process.env.TOKEN_SECRET}
using ES6 String Literals.
Yes, that worked for me. Go ahead and try it out.
explicitly configure dotenv in NestJS to solve error
Ooooh, oh! Since NestJS uses dotenv under the hood, you could easily use ConfigService or configure dotenv by changing some files.
jwt.strategy.ts
import * as dotenv from 'dotenv';
dotenv.config();
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
secretOrKey: process.env.TOKEN_SECRET,
});
}
}
auth.module.ts
import * as dotenv from 'dotenv';
dotenv.config();
@Module({
imports: [
JwtModule.register({
secret: process.env.JWT_SECRET,
}),
],
})
Let me know in the comments if it works for you!
Top comments (13)
To whomever might read this:
DO NOT use ES6 String Literals
This will set your secret to "undefined" WHENEVER process.env.ANY_VARIABLE fails to throw a result either by a typo or by a configuration issue. The actual solution is to add
As early as possible in your application so your environment variables are initialized. This would tipically be on index.js|ts, main.js|ts or server.js|ts, depending on your app. Go ahead and console log your JwtService
and see how if you dont add those 2 lines the secret will not be the one on the .env file.
Again, using template literals will just prevent the app from throwing an error by setting a different secret ("undefined") which would allow anyone to sign tokens and get unwarranted access to your app and you user's accounts.
Thanks for pointing this out!
Thank you!
Thank you, it helped me a lot!!
Wow! I'm glad to hear this.
Btw, I just followed you on GitHub @brunahirano . Nice repos you have on there!
Yea man! This saved me. Thank you
You're welcome. I'm happy you find it useful.
This issue is so strange. But thank you for the solution.
I'm glad I was able to help
if i'm getting this error on production environment? i mean locally works fine but i have my project deployed on aws and when i do a request to my endpoint, I'm getting the error
WOW, I can't thank you enough
You're welcome.