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"
}
}
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With