Basic Authentication in Node.js using HTTP Header
Last Updated :
08 Jan, 2025
Basic Authentication is a simple authentication method where the client sends a username and password encoded in base64 format in the HTTP request header.The basic authentication in the Node.js application can be done with the help express.js framework. Express.js framework is mainly used in Node.js application because of its help in handling and routing different types of requests and responses made by the client using different Middleware.
Working
HTTP WWW-Authenticate header is a response-type header and it serves as a support for various authentication mechanisms which are important to control access to pages and other resources as well.
Explanation of the Authentication:

Steps to Set up authentication using HTTP Header
Module Installation: Install the express module using the following command.
npm install express

Project structure:
Project StructureExample: This example sets up a Node.js Express server with basic authentication, requiring clients to provide valid credentials before accessing static files in the public
directory.
JavaScript
// Filename- index.js
// Requiring module
const express = require("express");
const fs = require("fs");
const path = require('path');
const app = express();
function authentication(req, res, next) {
const authheader = req.headers.authorization;
console.log(req.headers);
if (!authheader) {
let err = new Error('You are not authenticated!');
res.setHeader('WWW-Authenticate', 'Basic');
err.status = 401;
return next(err)
}
const auth = new Buffer.from(authheader.split(' ')[1],
'base64').toString().split(':');
const user = auth[0];
const pass = auth[1];
if (user == 'admin' && pass == 'password') {
// If Authorized user
next();
} else {
let err = new Error('You are not authenticated!');
res.setHeader('WWW-Authenticate', 'Basic');
err.status = 401;
return next(err);
}
}
// First step is the authentication of the client
app.use(authentication)
app.use(express.static(path.join(__dirname, 'public')));
// Server setup
app.listen((3000), () => {
console.log("Server is Running ");
})
Run index.js using the following command:
node index.js
- Open any browser with http://localhost:3000 location in a private window(in order to avoid a saved password and username). A pop will occur near the address bar. Fill in the username and password that are mention in the code.

- If the entered username and password match the mention, then location index.html will render on the browser.

Explanation: This middleware checks client authentication when accessing the server. Initially, it returns a 401 status code due to the absence of req.headers.authorization. The client then provides credentials, which are base64-encoded. The server decodes and verifies them; if correct, the next() method proceeds to the next middleware. If incorrect, the authentication prompt reappears.
Request Header Details:

Conclusion
Basic Authentication in Node.js using HTTP headers provides a straightforward method for securing access to resources. By implementing a middleware function in an Express server, you can enforce authentication and protect sensitive areas of your application. For production use, consider securing the connection with HTTPS to protect credentials during transmission.
Similar Reads
How to check user authentication in GET method using Node.js ? There are so many authentication methods like web token authentication, cookies based authentication, and many more. In this article, we will discuss one of the simplest authentication methods using express.js during handling clients get a request in node.js with the help of the HTTP headers. Appro
3 min read
How to set authorization headers in Postman? Web application security is vital, and JSON Web Tokens (JWT) play a key role in authentication and route protection. In this article we will learn how to create a secure backend with Node and Express using JWT, and then we will demonstrate how to set authorization headers in Postman for effective AP
3 min read
Node.js http.ClientRequest.getHeader() API The http.ClientRequest.getHeader() is  an inbuilt application programming interface of class ClientRequest within http module which is used to get the header object of the particular header name. Syntax: const request.getHeader(name) Parameters: This method takes the name of the header as a paramete
2 min read
Node.js https.request() Function Https request function in Node is used to make the http request over secure http or https. It provide more control to the request like setting headers, http methods, adding request data and handle the responses.https.request(options, callback)It is a part of https module and allows to send different
2 min read
Deploying Node.js Applications Deploying a NodeJS application can be a smooth process with the right tools and strategies. This article will guide you through the basics of deploying NodeJS applications.To show how to deploy a NodeJS app, we are first going to create a sample application for a better understanding of the process.
5 min read
How to Access HTTP Cookie in Node.js ? Cookies are small pieces of data sent by a server and stored on the client side, typically in the user's browser. They are often used to maintain stateful information such as user sessions, preferences, or tracking data. In Node.js, accessing and managing cookies is a common requirement for building
3 min read