Tania Rascia

Skip Navigation
Basic Authentication for an Express Node App (htpasswd)

Basic Authentication for an Express Node App (htpasswd)

 /  4 responses

I was struggling to find a simple way to add username and password authentication to a Node.js app running on an Express server, like .htpasswd for Apache. Finally, a StackOverflow answer helped me out.

To start, install the basic-auth package:

npm install basic-auth

Create an auth.js with the following code, changing username and password to whatever you want.

const auth = require('basic-auth');

const admins = { 'username': { password: 'password' }, };

module.exports = function (request, response, next) {
  var user = auth(request);
  if (!user || !admins[user.name] || admins[user.name].password !== user.pass) {
    response.set('WWW-Authenticate', 'Basic realm="example"');
    return response.status(401).send();
  }
  return next();
};

And in server.js, include this at the top of your file.

const auth = require('./auth');
const app = express();

app.use(auth);

Make sure to hide auth.js with a .gitignore file, and you’re all set!

Newsletter

Get updated when I create new content.
Unsubscribe whenever. Never any spam.

Note

I'm Tania. I turn down every ad, affiliate, and sponsor request I get. I write free resources that help thousands of people successfully become devs. If you enjoy my content, please consider supporting what I do.

Support my work

Write a response

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

All code will be displayed literally.

Discussion