Search code examples
mysqlnode.jsexpress

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


Solution

  • 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