NodeJs Series (Part#4) — Basic Authentication with “basic-auth” Module.
This article continues from the previous article, where we manually checked the username and password in the Authorization header. To simplify the process, we are now using the basic-auth module.
Get Zeeshan Ali’s stories in your inbox
Join Medium for free to get updates from this writer.
The basic-auth module in Node.js makes it easier to handle Basic Authentication by parsing the Authorization header and extracting the credentials
Step 1: Install the basic-auth Module
npm install basic-authStep 2: Implement Basic Authentication Using the basic-auth Module
- Open the app.js file
- Replace the below basicAuth Middleware in app.js
function basicAuth(req, res, next) {
const credentials = basicAuth(req); // Extract credentials from the Authorization header
if (!credentials) {
return res.status(401).json({ message: 'No credentials provided' });
}
// Set your own username and password
const validUsername = 'user';
const validPassword = 'password';
if (credentials.name === validUsername && credentials.pass === validPassword) {
next(); // Authentication passed, proceed to the route
} else {
return res.status(403).json({ message: 'Forbidden: Invalid credentials' });
}
}Step 2: Run the Server
node app.jsStep 3: Testing the API
- Open Postman.
- Select the method as GET and enter the URL
http://localhost:3000/api/secure-data. - Under the Authorization tab, select Basic Auth.
- Enter the username (
user) and password (password). - Send the request, and you should receive a response
{ "message": "This is a protected route, accessible only with valid credentials!" }Before proceeding further, let’s first understand what middleware is and how it works in the Next Article.






