DEV Community

Taylor Beseda
Taylor Beseda

Posted on

Express.js Basic Auth: Get it out the door!

Sometimes you need to roll out a prototype before it even has an authentication layer. Here's how to require a username and password for your application.

Important!

If it isn't obvious, this should be TEMPORARY!. A proper authentication layer should be added and sensitive data, like passwords, shouldn't be a part of an application's codebase. With that said...

Express Basic Auth

I'm going to assume some Node.js basics and that you're working with Express.

First, install the express-basic-auth dependency: npm i express-basic-auth.

Require the auth package where you create your app

const app = require('express')();
const basicAuth = require('express-basic-auth');

and tell Express your user(s)' credentials

app.use(basicAuth({
    users: { 'username': 'password' },
    challenge: true,
}));

The challenge option tells the browser to open a prompt so the user doesn't need to enter a URL prefix like username:password@....
Also, you can add several users to the users object.

Simple! Now ship it.

Top comments (0)