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

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.

Leave a Comment