Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"
    }
}

enter image description here

enter image description here

like image 315
mchomvu Avatar asked Nov 02 '19 17:11

mchomvu


2 Answers

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:

enter image description here

like image 178
SuleymanSah Avatar answered Nov 13 '22 11:11

SuleymanSah


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.

like image 29
Rabo Yusuf Avatar answered Nov 13 '22 12:11

Rabo Yusuf