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!

Note

Hi, my name is Tania Rascia. I've turned down every offer for advertisements or sponsored posts on this website. I write free resources that have helped thousands of people successfully transition into a web development career.

My committment is to no bullshit, no sponsored posts, no ads, and no paywalls. If you enjoy my content, please consider supporting what I do.

Support my work

Newsletter

New articles on web development every two weeks.

Write a response

Your email address will not be published.

All code will be displayed literally.

Discussion