Blog archives

Basic HTTP authentication in Node.js using the request module

29 comments

Here’s an easy way to use basic authentication while using the request library for Node.js.

Unfortunately request doesn’t come with an easy convenience parameter you can use, so you need to provide it by yourself. The common way is to add it as an extra HTTP header.

Let’s say you need to login to example.com using user and pass as your username/password.

    
var request = require('request'),
    username = "john",
    password = "1234",
    url = "http://www.example.com",
    auth = "Basic " + new Buffer(username + ":" + password).toString("base64");

request(
    {
        url : url,
        headers : {
            "Authorization" : auth
        }
    },
    function (error, response, body) {
        // Do more stuff with 'body' here
    }
);

This is pretty verbose. Fortunately, you can use a trick using the URL itself, as specified in RFC 1738. Simply pass the user/pass before the host with an @ sign.

var request = require('request'),
    username = "john",
    password = "1234",
    url = "http://" + username + ":" + password + "@www.example.com";

request(
    {
        url : url
    },
    function (error, response, body) {
        // Do more stuff with 'body' here
    }
);

Nice one huh?

Add a comment

29 comments