Freddy Bonda
Freddy Bonda

Reputation: 1259

secretOrPrivateKey must have a value

I am trying to learn nodejs and using jwt to create a token for a user. But I am getting this error on my server side: secretOrPrivateKey must have a value. It is a lot of code so I am going to give what I think is important (let me know if you need anything else):

user.js:

const config = require('./../config/config').get(process.env.NODE_ENV);
...
userSchema.methods.generateToken = function(callback) {
    console.log(config.SECRET); // THIS IS UNDEFINED
    var token = jwt.sign(this._id.toHexString(), config.SECRET);

    this.token = token;
    this.save(function(err, user) {
        if (err) return callback(err);
        callback(null, user)
    });
}

server.js:

app.post('/api/login', (req, res) => {
    User.findOne({'email': req.body.email}, (err, user) => {
        ...    
        user.generateToken((err, user) => {
            if (err) return res.status(400).send(err);

            res.cookie('auth', user.token).json({
                isAuth: true,
                id: user._id
            })
        })
    })
})

config.js:

const config = {
    production: {
        SECRET: process.env.SECRET,
        DATABASE: process.env.MONGODB_URI
    },
    default: {
        SECRET: 'SUPER_SECRET-PASSWORD!123?',
        DATABASE: 'mongodb://localhost:27017/feedback'
    }
}

exports.get = function get(env) {
    return config[env] || config.default
}

Upvotes: 4

Views: 33322

Answers (3)

Ann
Ann

Reputation: 21

In my case, I have this folder structure.

  • Project

    • frontend

    • backend

      • index.js
      • .env

I ran into the error "secretOrPrivateKey must have a value" because the terminal was in Project folder and I ran nodemon backend/index.js. I wasn't in the correct folder with .env file to run the backend. cd backend && nodemon index.js helps

Upvotes: 2

Matt Kuhns
Matt Kuhns

Reputation: 1368

I think your calling of node is probably wrong. Try node server.js and you should get the default config. You can also put a console.log in the exports.get() to see what it is sending in as an environment variable.

Upvotes: 4

xrobert35
xrobert35

Reputation: 2556

I think you have a problem with your config. The only thing you export is a function get. so config.SECRET is empty. you should have write config.get().SECRET

Upvotes: 2

Related Questions