Protect your NodeJS/Express routes with HTTP Basic Auth

Not all parts of your website or REST APIs you do require same level of protection. For example, a GET /api/dimounes is pretty harmless.

The Express/NodeJS code for such a route may be like follows:

  var rows = // Get the people from database, file or anywhere

Let’s say now you want to add more ‘dimoune’. We create a new route for it but we’ll use HTTP POST verb instead of GET.

app.use(bodyParser.urlencoded({extended: true }));
  var sql = "INSERT INTO dimounes (name,sex) VALUES ('" + + "' , " + + ");";
  // run sql or mongo insert

Problem here is everyone can do POST request and spam your database to corrupt it. Let’s protect the POST route so that it requires the user to authenticate.

$ npm install http-auth --save

Let’s define our username and password

var auth = require('http-auth');
var basic = auth.basic({
        realm: "Protected Area"
    }, function (username, password, callback) { // Custom authentication method.
        callback(username === "nayar" && password === "mydumbpassword");

All we have to do is add auth.connect(basic) as a middleware in our routes we want to protect'/api/dimounes/',auth.connect(basic),function(req,res){
  var sql = "INSERT INTO dimounes (name,sex) VALUES ('" + + "' , " + + ");";
  // run sql or mongo insert

And there you go! Let’s try it with AJAX calls with jQuery 😉

  method: "post",
  url: "/api/dimounes/",
  data: {
    name : "Nayar",
    sex: "male"
  success: function( data ) {

You shall get a popup in your browser asking for your username and password. If you are using curl, just add the credentials using the -u

curl -nayar:mydumbpassword -H "Content-Type:application/json" -X POST --data '{"name":"nayar","sex":"male"}'

NOTE: As we saw in this article (click), Express doesn’t parse HTTP body, we have to add this line at the top for the above command to work in curl.


Leave a Reply

Your email address will not be published. Required fields are marked *