Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
sending cookies from http.createServer()

sending cookies from http.createServer()

To send cookies, we can use the cookie module's cookie.serialize() function:

var cookie = require('cookie');
var http = require('http');

var server = http.createServer(function (req, res) {
    res.setHeader('set-cookie', cookie.serialize('greeting', 'beep boop'));
    res.end('I sent you a cookie in an HTTP header!\n');
});
server.listen(8000);

First start the server:

node server.js

then in another terminal, we can use curl -i to see what the server sent us. The -i field tells curl to print out the http headers that our server sent in addition to the page content:

$ curl -i http://localhost:8000
HTTP/1.1 200 OK
set-cookie: greeting=beep%20boop
Date: Mon, 13 Oct 2014 08:57:35 GMT
Connection: keep-alive
Transfer-Encoding: chunked

I sent you a cookie in an HTTP header!

The %20 in beep%20boop is called urlencoding. Cookie parsers understand this encoding and can convert it back to our original message: 'beep boop'.

expiry

By default, cookies expire as soon as the user closes their browser.

To make the cookie last longer than a single browser session, you can set the expires parameter as a third argument to cookie.serialize(). This code will set a cookie that will expire in 90 days:

var cookie = require('cookie');
var http = require('http');

var server = http.createServer(function (req, res) {
    res.setHeader('set-cookie', cookie.serialize('greeting', 'beep boop', {
        expires: new Date(Date.now() + 1000*60*60*24*90)
    }));
    res.end('I sent you a cookie in an HTTP header!\n');
});
server.listen(8000);

The expires parameter expects a Date object that we can create with the expression new Date(Date.now() + 1000*60*60*24*90). The new Date(...) constructor accepts a timestamp in milliseconds, so we get the current time in milliseconds (Date.now()) and add that to:

  • 90 days
  • times 24 hours per day
  • times 60 minutes per hour
  • times 60 seconds per minute
  • times 1000 milliseconds per second

so that our cookie will expire in 90 days.

see also

[parsing cookies from http.createServer()]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment