Showing posts with label rest. Show all posts
Showing posts with label rest. Show all posts

Friday, August 3, 2012

Passing Cookies to a Node.js REST Client

In Node.js if you want to pass the current user's Cookies to a REST call your making from the server here's a simple way to do it:

var cookies =, function(val, key) {
    return key + "=" + encodeURIComponent(val);
}).join("; ");

rest.get("", {
    headers: {
        Cookie: cookies,
        "Content-Type": "application/json"
  }).on("complete", function(data) {
    return console.log(data);

This example uses the popular Restler library, but I assume you could do something similar with other libraries or without using a library.

CAUTION: I'm using encodeURIComponent on the cookie value. Ruby on Rails seems to expect their cookies to be encoded like this. On the other hand, I've looked throw a few Node.js libraries that deal with cookies and they don't seem to manipulate the value at all. So you can play with adding or removing encodeURIComponent.

If you start to get errors when making the REST request, be sure to check the cookie encoding/format versus what Firebug sends on a normal request to the site. Pay particular attention to any special characters.