HTTP Basic Authentication with Express

Updated: 03 September 2023

In a new file, define the middleware using the following:

1
const authenticate = (req, res, next) => {
2
const auth = { login: process.env.BASIC_UN, password: process.env.BASIC_PW }
3
4
const b64auth = (req.headers.authorization || '').split(' ')[1] || ''
5
const [login, password] = new Buffer(b64auth, 'base64').toString().split(':')
6
7
// Verify login and password are set and correct
8
if (login && password && login === auth.login && password === auth.password) {
9
// Access granted...
10
return next()
11
} else {
12
res.status(401).send('Authentication required.') // custom message
13
}
14
}
15
16
module.exports = authenticate

The middleware can then be used in an Express Endpoint or for all endponits using either:

  1. For all endpoints
1
const auth = require('./authorize.js')
2
3
app.use(auth)
  1. For a specific endpoint
1
const auth = require('./authorize.js')
2
3
app.get('/secret-stuff', auth, secretStuffHandler)