Search code examples
node.jsexpressjwt

Where do i store my jwt for authorization?


I searched many article for days i find they sending the token like this

res.json({token})

and using a middleware like this

function verifyToken(req, res, next){
  const authHeader = req.headers['authorization']
  const token = authHeader && authHeader.split(' ')[1]

  if (token == null) return res.sendStatus(401); // No token provided

  if(jwt.verify(token,process.env.JWT_SECRET)){
    next()
  }
}

How do they put that token in the req.headers['authorization']

when i console.log that it gives me only undefined

the res.json({token}) only send me to the token


Solution

  • I'm suspecting you're working on client side to send token to server side, the best way to actually store token in real production level is to put in Cookie with Httponly flag and set your domain in the cookie.

    If your website is vulnerable to any security, then using LocalStorage your website will be vulnerable to token theft and that's the worst you'd want to happen.
    There's article that explain how to achieve that: https://www.saurabhmisra.dev/store-jwt-token-http-only-cookie/