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.


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.


If you're using the express library, as many node.js developers do, there is an easier way. Check the Express.js documentation page for more information.

The parsing example above works but express gives you a nice function to take care of that:

app.use(express.cookieParser());

To set a cookie:

res.cookie('cookiename', 'cookievalue', { maxAge: 900000, httpOnly: true });

To clear the cookie:

res.clearCookie('cookiename');

RevNoah had the best answer with the suggestion of using Express's cookie parser. But, that answer is now 3 years old and is out of date.

Using Express, you can read a cookie as follows

var express = require('express');
var cookieParser = require('cookie-parser');
var app = express();
app.use(cookieParser());
app.get('/myapi', function(req, resp) {
   console.log(req.cookies['Your-Cookie-Name-Here']);
})

And update your package.json with the following, substituting the appropriate relatively latest versions.

"dependencies": {
    "express": "4.12.3",
    "cookie-parser": "1.4.0"
  },

More operations like setting and parsing cookies are described here and here