How I do Basic Authentication with Axios in Nodejs

Published 2020-05-14

Macbook with Visual Code Open

This post serves as a reminder to myself as I have been forgetting how to do Basic Authentication with Axios.

Thus, this post serves as the memory boost.

Basic Authentication is an authentication scheme for HTTP protocol. We can always found them from the Request Header, Authorization field.

Those value start with Basic ***randomstring***. These value usually constructed using base64 encoding to username followed by colon, and password like the example below.


Encode to Base64 Without External Library

const username = 'username'; const password = 'password'; const encodedBase64Token = Buffer.from(`${username}:${password}`).toString('base64'); const authorization = `Basic ${encodedBase64Token}`;

Setting to Axios Headers

After you have encoded the token and have the authorization string, let's assign it to your request header.

const response = await axios({ url: '', method: 'post', headers: { Authorization: authorization, }, data: {} // Request Body if you have });

That's how I do basic authentication in Nodejs using Axios.


Photo by Maxwell Nelson on Unsplash


  • Swagger Basic Auth Doc
  • Practical article by Flavio