DEV Community

How to solve "secretOrPrivateKey must have a value" in Node.js

Emmanuel Aiyenigba on March 07, 2022

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 t...
Collapse
 
johalternate profile image
Johanderson • • Edited

To whomever might read this:

DO NOT use string interpolation

`${process.env.TOKEN_SECRET}`
Enter fullscreen mode Exit fullscreen mode

This will set your secret to "undefined" WHENEVER process.env.ANY_VARIABLE is undefined either by a typo or by a configuration issue. The actual solution is to add

import * as dotenv from 'dotenv';
dotenv.config();
Enter fullscreen mode Exit fullscreen mode

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

console.log(this.jwtService);
Enter fullscreen mode Exit fullscreen mode

and see how if you dont add those 2 lines the secret will not be the one on the .env file.

Again, using string interpolation 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.

Collapse
 
emmanuelthecoder profile image
Emmanuel Aiyenigba •

Thanks for pointing this out!

Collapse
 
casualr profile image
Casual •

What a legend

Collapse
 
brunahirano profile image
brunahirano •

Thank you, it helped me a lot!!

Collapse
 
emmanuelthecoder profile image
Emmanuel Aiyenigba •

Wow! I'm glad to hear this.

Collapse
 
emmanuelthecoder profile image
Emmanuel Aiyenigba •

Btw, I just followed you on GitHub @brunahirano . Nice repos you have on there!

Collapse
 
lucianogmoraesjr profile image
Luciano Moraes Jr. •

Yea man! This saved me. Thank you

Collapse
 
emmanuelthecoder profile image
Emmanuel Aiyenigba •

You're welcome. I'm happy you find it useful.

Collapse
 
necolanch profile image
Nicholas Cruz •

This issue is so strange. But thank you for the solution.

Collapse
 
emmanuelthecoder profile image
Emmanuel Aiyenigba •

I'm glad I was able to help

Collapse
 
jcmn182 profile image
jcmn182 •

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

Collapse
 
nahid570 profile image
Nahid Faraji •

WOW, I can't thank you enough

Collapse
 
emmanuelthecoder profile image
Emmanuel Aiyenigba •

You're welcome.