Node.js: enable HTTP authentication in ExpressJS

Node.js: enable HTTP authentication in ExpressJS

In Node.js we can enable HTTP authentication in ExpressJS.

In Node.js we can enable HTTP authentication in ExpressJS.

We need a specific module:


npm install http-auth --save

We can use this module as a middleware, either on a single route or on the whole app:


'use strict';

const express = require('express');
const app = express();
const auth = require('http-auth');

const basic = auth.basic({
	realm: 'Login',
	file: __dirname + '/.htpasswd'
});

app.get('/admin', auth.connect(basic), (req, res)=> {
    //...
});

The .htpasswd file can be generated with the htpasswd utility from the command line. Alternatively, you can use the following online tool.

Note that the .htpasswd file must be readable by Node so if you're generating it as a sudoer user, don't forget to assign its ownership to the appropriate user. Path is also relevant.