Encode credentials to base64 using Javascript


May 21, 2023

let username = 'username';
let password = 'password';
let auth = btoa(username + ':' + password);

fetch('https://my-app.com/auth', {
  headers: { Authorization: 'Basic ' + auth },
})
  .then(function (response) {
    if (response.ok) return response.json();
    throw response;
  })
  .then(function (data) {
    console.log(data);
  })
  .catch(function (error) {
    console.warn(error);
  });

NOTE: btoa is not supported in a nodejs server environment. You can use Buffer from nodeJS instead.

Voila! it's done.

Hope it was helpful. Thank you.