Search code examples
node.jsauthenticationcookiesjwtexpress-jwt

How to send JWT token to Cookie and use in another routes?


This is my Login Controller(JWT)

const token = jwt.sign({ _id: user._id }, secret);
res.header('auth-token', token).redirect('/home');

This is my Middleware for JWT Token

module.exports = (req, res, next)=>{
    const token = req.header('auth-token');
    if(!token){
        return res.send('Denied');
    }
    try {
        const verified = jwt.verify(token, secret);
        req.user = verified;
        next();
    } catch (error) {
        console.log('JWT Error', error)
    }
}

This is my Route Code

const verify = require('../middlewares/tokenMiddleware');
router.get('/home', verify, (req, res, next)=>{
  res.render('home');
});

A token is assigning and can visible on the login route. But I want to send it to a cookie so that I can use it on all routes for user auth.


Solution

  • You have to install the cookie parser package to set and read cookies from a request. Reference : Express (Cookie Parser) After installing the package you can simply use it inside your node application.
    Setting cookies :-

    const cookieParser = require('cookie-parser');
    
    app.use(cookieParser());
    res.cookie('auth-token', token, [options]);    // You can look up the options at the API reference
    

    Reading cookies :-

    const token = req.cookies['auth-token'];
    

    As an alternative, to set cookies without using the cookie parser package, you have to use the 'Set-Cookie : header in order to set cookies using an HTTP header.