ExpressJs JWT secret or public key must be provided

Emre picture Emre · Sep 17, 2018 · Viewed 9.4k times · Source

I would like to make check-auth but return to me

JsonWebTokenError: secret or public key must be provided

I can take token successful

how can i fix this?

I am following this tutorial ;

https://www.youtube.com/watch?v=8Ip0pcwbWYM&t=633s

const jwt = require('jsonwebtoken');
module.exports = (req, res, next) => {
  try {
    const token = req.headers.authorization.split(" ")[1];
    console.log(token);
    const decoded = jwt.verify(token, process.env.JWT_KEY);
    req.userData = decoded;
    next();
  } catch (error) {
    console.log(error);
    return res.status(401).json({
      message: 'Auth failed'
    })
  }
}

Answer

James picture James · Sep 18, 2018

process.env global variable is injected by the Node at runtime for your application to use. You need to create a new env file to store those environment variables.

That said, You must declare your variable JWT_KEY inside a separate js archive. If you're using Nodemon just create a archive nodemon.json (works like env in this case) and declare your variables like this:

{ 
"env": { 
  "JWT_KEY": value,
  ...
  }
}