I'm building a blog using node.js (no Express) where users can comment on posts. I require users to log in before they can comment, so I'm using JSON Web Tokens (created via the jsonwebtoken node module) to authenticate their log in status. When they successfully log in, a cookie containing the JWT is added to the page response header, like this:

res.writeHead(302, {"Set-Cookie": `jwt=${MYTOKENISHERE}; max-age=9000; HttpOnly`, 
Location: "/blog/blog.html"
}); 
res.end();

When I inspect the webpage's cookies in my browser, I can see the encoded JWT - so far, so good:

Link to screenshot: https://i.ibb.co/MBzw5jX/cookies.png

The problem comes when a logged-in user tries to post a comment. I'm handling this with a POST request via an HTML form, but for some reason the JWT doesn't appear in the request object that reaches my server/router. Here is a snippet from my router code:

const cookie = require('cookie');

if (method === "POST") {
    if (request.url.includes("/create/comment")) {
        let cookies = cookie.parse(request.headers.cookie);
        console.log("COOKIES :", cookies);
        }
    }
//Expected console.log() output: 

COOKIES: { 
    jwt: [THE ENCODED JWT STRING],
    _ga: 'GA1.1.1615891668.1553812077', // random google analytics cookie
    gid: 'GA1.1.1919987325.1555742391' // random google analytics cookie
}
// Actual console.log() output: 

COOKIES: { 
    _ga: 'GA1.1.1615891668.1553812077', // random google analytics cookie
    gid: 'GA1.1.1919987325.1555742391' // random google analytics cookie 
}

As you can see, the JWT is missing. I have tried replacing the HTML form request with an XmlHttpRequest from the DOM, but I still get the same result. The JWT appears fine in GET request headers, I'm only having this issue with POST requests.

What is the best way to pass an encoded JSON Web Token string from the client to the server?

0 Answers