'Error: secretOrPrivateKey must have a value
I am using jwt to create token, but when i login via postman I get the error "Error: secretOrPrivateKey must have a value" from my console. I have attached my login code. Please anyone who can help me
exports.login = (req, res, next) => {
User.findOne({
where: {
email: req.body.email
}
})
.then(user => {
if (!user) {
return res.status(401).json({
message:
"Auth failed!! either the account does't exist or you entered a wrong account"
});
}
bcrypt.compare(req.body.password, user.password, (err, result) => {
if (err) {
return res.status(401).json({
message: "Auth failed",
token: token
});
}
if (result) {
const token = jwt.sign(
{
email: user.email,
password: user.id
},
process.env.JWT_KEY,
{
expiresIn: "1h"
}
);
res.status(200).json({
message: "Auth granted, welcome!",
token: token
});
}
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
};
this is my env.json file
{
"env":{
"MYSQL":"jllgshllWEUJHGHYJkjsfjds90",
"JWT_KEY": "secret"
}
}
Solution 1:[1]
It looks like your application can't read the environment variable properly.
I don't know which package you are using to load environment variables but the simplest way is using dotenv package.
After installing it with npm i dotenv, import it as early as possible in your application main file like this:
require("dotenv").config();
Create .env file in your application root folder with this content ( as you see the format is key=value)
MYSQL=jllgshllWEUJHGHYJkjsfjds90
JWT_KEY=secret
Then you can access their values like you already did:
process.env.JWT_KEY
.env file:
Solution 2:[2]
Remove the process.env.JWT_SECRET_KEY and do it this way: ${process.env.JWT_SECRET_KEY}
wrap it with backtick.
It solved the problem for me.
Solution 3:[3]
It works for me only if I concatenate it with an empty string like this:
"" + process.env.JWT_KEY
Solution 4:[4]
Had this issue with NestJS when trying to rely on process.env.X
. Supposedly @nestjs/config
uses dotenv
in the background but it doesn't work as expected. I either had to use ConfigService
or explicitly configure dotenv
in the given files:
jwt.strategy.ts
import * as dotenv from 'dotenv';
dotenv.config();
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
secretOrKey: process.env.JWT_SECRET,
});
}
}
or
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(configService: ConfigService) {
super({
secretOrKey: configService.get<string>('JWT_SECRET'),
});
}
}
auth.module.ts
import * as dotenv from 'dotenv';
dotenv.config();
@Module({
imports: [
JwtModule.register({
secret: process.env.JWT_SECRET,
}),
],
})
or
@Module({
imports: [
JwtModule.registerAsync({
imports: [ConfigModule]
useFactory: async (configService: ConfigService) => {
return {
secret: configService.get<string>('JWT_SECRET'),
};
},
inject: [ConfigService],
}),
],
})
Solution 5:[5]
simply remove the process.env.JWT_KEY and replace with "secret key using" ES6 String Literals
${process.env.JWT_SECRET_KEY}
it solves this for me
Solution 6:[6]
Are you sure process.env.JWT_KEY
has a valid value? I believe it is undefined
or null
.
Solution 7:[7]
Put the require('dotenv').config() at the top of the server.js file This solved for me
Solution 8:[8]
You can try this, it works for me. "" + process.env.JWT_KEY
Solution 9:[9]
I simply removed process.env.JWT_KEY and replace with "secret" and its working fine.
Solution 10:[10]
- Just add back quotes `` and use the syntax
${process.env.SECRET_KEY}
in them. - I also advise you to use the cross-env package, after installing which you can make two files with environment variables .development.env and .production.env
To configure cross-env
, just paste this into a package.json
"scripts"
field:
"start": "cross-env NODE_ENV = production nest start",
"start:dev": "cross-env NODE_ENV = development nest start --watch"
it is for nestjs
Solution 11:[11]
To chime in on this, I found this error was being caused by the contents of the key I was trying to use. I regularly use a "password generator" for such strings, and it had given me the following to use:
<B#LCK$^\7(T^fuaQemeR&6s:#@AAwe@?T,c'=+kxT?euCP27R/D=uRm893$=^_h^f={c.)MD#[%zg}$K8_D#D-_/
tb2?Q>RFr(}H:Fp#{&yNFt@2Y<K\GB28unz
if the above is placed in between back ticks or speech marks it will not be able to be parsed as a string and will therefore cause this error as described above.
As an extra level of de-bugging make sure you first wrap your key in backticks or parenthesis in order to make sure that an un-parsable string isn't the issue.
Solution 12:[12]
You can also try and specify an object with a property the path to the configuration file like
require("dotenv").config({path: '/path_to_env_file'});
Solution 13:[13]
I also had the same issue I came to realize that the issue was that I didn't include dotenv package
so
import * as dotenv from 'dotenv';
then put dotenv.config()
on top before any other implementation
Solution 14:[14]
IN token REPLACE GRAB THE FOLLOWING IN BACKTICKS. THIS SYNTEX WORKED FOR ME TRY THIS.
${process.env.JWT_SECRET_KEY}
Solution 15:[15]
step 1: install dotenv
step 2: import that in app.js:
const dotenv = require("dotenv");
step 3:
dotenv.config(`${process.env.SECRET_KEY}`);
your issue will solve
Solution 16:[16]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow