Search code examples
javascriptnode.jscookiesnpmsetcookie

Access cookie values set by node server in the front end


Currently am using node package coockie to set cookies from the backend like below

        res.setHeader('Set-Cookie', cookie.serialize('token', token, {
            maxAge: 60 * 60 * 24 * 7 // 1 week
        }));

so I can access the token from the front end side like below

var ca = document.cookie.split(';').map(function (x) {
         return x.trim().split('=');
         }).reduce(function (a, b) {
              a[b[0]] = b[1];
              return a;
         }, {})["token"];

But when I set another one from the back end the second one will not set on the as a cookie.So as a solution for this I used

 res.cookie('refreshtoken', refreshToken, { maxAge: 60 * 60 * 24 * 7 , httpOnly: true });

so from this I can set any no of cookie but the problem is this cookies cannot be accessed from the front end side.

So is there away to set more than one cookie from the backend and access all of them from the front end


Solution

  • httpOnly: true
    

    This tells the browser that it should make the cookie available only to HTTP (i.e. not to client side JavaScript).

    To read it with client side JS, simply don't do that.

    Set the value to false instead.