Search code examples
javascriptnode.jscookieshttpserver

Get and Set a Single Cookie with Node.js HTTP Server


I want to be able to set a single cookie, and read that single cookie with each request made to the nodejs server instance. Can it be done in a few lines of code, without the need to pull in a third party lib?

var http = require('http');

http.createServer(function (request, response) {
  response.writeHead(200, {'Content-Type': 'text/plain'});
  response.end('Hello World\n');
}).listen(8124);

console.log('Server running at http://127.0.0.1:8124/');

Just trying to take the above code directly from nodejs.org, and work a cookie into it.


Solution

  • There is no quick function access to getting/setting cookies, so I came up with the following hack:

    const http = require('http');
    
    function parseCookies (request) {
        const list = {};
        const cookieHeader = request.headers?.cookie;
        if (!cookieHeader) return list;
    
        cookieHeader.split(`;`).forEach(function(cookie) {
            let [ name, ...rest] = cookie.split(`=`);
            name = name?.trim();
            if (!name) return;
            const value = rest.join(`=`).trim();
            if (!value) return;
            list[name] = decodeURIComponent(value);
        });
    
        return list;
    }
    
    const server = http.createServer(function (request, response) {
        // To Read a Cookie
        const cookies = parseCookies(request);
    
        // To Write a Cookie
        response.writeHead(200, {
            "Set-Cookie": `mycookie=test`,
            "Content-Type": `text/plain`
        });
    
        response.end(`Hello World\n`);
    }).listen(8124);
    
    const {address, port} = server.address();
    console.log(`Server running at http://${address}:${port}`);
    

    This will store all cookies into the cookies object, and you need to set cookies when you write the head.