Make Basic Authentication Request in Node.js

Contents
In this article, you will learn how to make a basic authentication request in Node.js.
Making a basic authentication request in Node.js
In Node.js, you can make a basic authentication request by setting the Authorization header with a Base64-encoded string of the username and password. The http module provides a simple way to set this header when making HTTP requests.
Here’s an example of how to make a basic authentication request using the http module in Node.js:
const http = require('http');
const username = 'myusername';
const password = 'mypassword';
const auth = `${username}:${password}`;
const encodedAuth = Buffer.from(auth).toString('base64');
const options = {
hostname: 'www.example.com',
port: 80,
path: '/api/data',
headers: {
'Authorization': `Basic ${encodedAuth}`
}
};
http.get(options, function(res) {
let responseData = '';
res.on('data', function(chunk) {
responseData += chunk;
});
res.on('end', function() {
console.log(responseData);
});
}).on('error', function(error) {
console.error(error);
});
In this example, we first define the username and password for the basic authentication request. We then concatenate the username and password into a single string with a colon separator, and encode the string using the Buffer.from() method and the Base64 encoding format.
We define the options object with the hostname, port, path, and Authorization header that contains the Base64-encoded authentication string. We then use the http.get() method to send a GET request with the options object. We listen for the data event on the response object to receive the response data, and concatenate each chunk of data into a single string using the += operator. Finally, we log the response data to the console when the end event is fired.
If an error occurs, we log the error to the console using the error event listener.
Note that basic authentication is not secure, as the authentication string can be easily decoded from the Base64-encoded string. For better security, consider using HTTPS with SSL/TLS encryption and more secure authentication methods such as OAuth or JSON Web Tokens (JWTs).