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



Question:

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:1

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

var http = require('http');    function parseCookies (request) {      var list = {},          rc = request.headers.cookie;        rc && rc.split(';').forEach(function( cookie ) {          var parts = cookie.split('=');          list[parts.shift().trim()] = decodeURI(parts.join('='));      });        return list;  }      http.createServer(function (request, response) {      // To Read a Cookie    var 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);    console.log('Server running at http://127.0.0.1:8124/');  

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


Solution:2

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');  


Solution:3

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


Solution:4

You can use the "cookies" npm module, which has a comprehensive set of features.

Documentation and examples at:
https://github.com/jed/cookies


Solution:5

Cookies are transfered through HTTP-Headers
You'll only have to parse the request-headers and put response-headers.


Solution:6

To get a cookie splitter to work with cookies that have '=' in the cookie values:

var get_cookies = function(request) {    var cookies = {};    request.headers && request.headers.cookie.split(';').forEach(function(cookie) {      var parts = cookie.match(/(.*?)=(.*)$/)      cookies[ parts[1].trim() ] = (parts[2] || '').trim();    });    return cookies;  };  

then to get an individual cookie:

get_cookies(request)['my_cookie']  


Solution:7

As an enhancement to @Corey Hart's answer, I've rewritten the parseCookies() using:

Here's the working example:

var http = require('http');    function parseCookies(cookie) {      return cookie.split(';').reduce(          function(prev, curr) {              var m = / *([^=]+)=(.*)/.exec(curr);              var key = m[1];              var value = decodeURIComponent(m[2]);              prev[key] = value;              return prev;          },          { }      );  }    function stringifyCookies(cookies) {      var list = [ ];      for (var key in cookies) {          list.push(key + '=' + encodeURIComponent(cookies[key]));      }      return list.join('; ');  }    http.createServer(function (request, response) {    var cookies = parseCookies(request.headers.cookie);    console.log('Input cookies: ', cookies);    cookies.search = 'google';    if (cookies.counter)      cookies.counter++;    else      cookies.counter = 1;    console.log('Output cookies: ', cookies);    response.writeHead(200, {      'Set-Cookie': stringifyCookies(cookies),      'Content-Type': 'text/plain'    });    response.end('Hello World\n');  }).listen(1234);  

I also note that the OP uses the http module. If the OP was using restify, he can make use of restify-cookies:

var CookieParser = require('restify-cookies');  var Restify = require('restify');  var server = Restify.createServer();  server.use(CookieParser.parse);  server.get('/', function(req, res, next){    var cookies = req.cookies; // Gets read-only cookies from the request    res.setCookie('my-new-cookie', 'Hi There'); // Adds a new cookie to the response    res.send(JSON.stringify(cookies));  });  server.listen(8080);  


Solution:8

Here's a neat copy-n-paste patch for managing cookies in node. I'll do this in CoffeeScript, for the beauty.

http = require 'http'    http.IncomingMessage::getCookie = (name) ->    cookies = {}    this.headers.cookie && this.headers.cookie.split(';').forEach (cookie) ->      parts = cookie.split '='      cookies[parts[0].trim()] = (parts[1] || '').trim()      return      return cookies[name] || null    http.IncomingMessage::getCookies = ->    cookies = {}    this.headers.cookie && this.headers.cookie.split(';').forEach (cookie) ->      parts = cookie.split '='      cookies[parts[0].trim()] = (parts[1] || '').trim()      return      return cookies    http.OutgoingMessage::setCookie = (name, value, exdays, domain, path) ->    cookies = this.getHeader 'Set-Cookie'    if typeof cookies isnt 'object'      cookies = []      exdate = new Date()    exdate.setDate(exdate.getDate() + exdays);    cookieText = name+'='+value+';expires='+exdate.toUTCString()+';'    if domain      cookieText += 'domain='+domain+';'    if path      cookieText += 'path='+path+';'      cookies.push cookieText    this.setHeader 'Set-Cookie', cookies    return  

Now you'll be able to handle cookies just as you'd expect:

server = http.createServer (request, response) ->    #get individually    cookieValue = request.getCookie 'testCookie'    console.log 'testCookie\'s value is '+cookieValue      #get altogether    allCookies = request.getCookies()    console.log allCookies      #set    response.setCookie 'newCookie', 'cookieValue', 30      response.end 'I luvs da cookies';    return    server.listen 8080  


Solution:9

If you don't care what's in the cookie and you just want to use it, try this clean approach using request (a popular node module):

var request = require('request');  var j = request.jar();  var request = request.defaults({jar:j});  request('http://www.google.com', function () {    request('http://images.google.com', function (error, response, body){       // this request will will have the cookie which first request received       // do stuff    });  });  


Solution:10

To get a single cookie this code would be faster than parsing all the cookies:

getSingleCookie = (cookie, name) ->    vIx = cookie.indexOf "#{name}="    if vIx != -1      egalIx = vIx+name.length+1      colIx = cookie.indexOf ';', egalIx      v = if colIx == -1        cookie.substring egalIx      else        cookie.substring egalIx, colIx      return v  

Should be use like :

getSingleCookie request.headers, 'my_cookie'  


Solution:11

First one needs to create cookie (I have wrapped token inside cookie as an example) and then set it in response.To use the cookie in following way install cookieParser

app.use(cookieParser());  

The browser will have it saved in its 'Resource' tab and will be used for every request thereafter taking the initial URL as base

var token = student.generateToken('authentication');          res.cookie('token', token, {              expires: new Date(Date.now() + 9999999),              httpOnly: false          }).status(200).send();  

To get cookie from a request on the server side is easy too.You have to extract the cookie from request by calling 'cookie' property of the request object.

var token = req.cookies.token; // Retrieving Token stored in cookies  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »