Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}
like image 994
Freddy Bonda Avatar asked Oct 18 '25 15:10

Freddy Bonda


1 Answers

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.

like image 172
Matt Kuhns Avatar answered Oct 20 '25 04:10

Matt Kuhns



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!