Basic authentication with fetch?

Solution 1:

You are missing a space between Basic and the encoded username and password.

headers.set('Authorization', 'Basic ' + base64.encode(username + ":" + password));

Solution 2:

A solution without dependencies.

Node

headers.set('Authorization', 'Basic ' + Buffer.from(username + ":" + password).toString('base64'));

Browser

headers.set('Authorization', 'Basic ' + btoa(username + ":" + password));

Solution 3:

In pure JavaScript you can also use btoa instead of base64.encode():

headers.set('Authorization', 'Basic ' + btoa(username + ":" + password));

Note that this will only work with ASCII characters.

If you have to handle different encodings, see the linked btoa documentation.

Solution 4:

A simple example for copy-pasting into Chrome console:

fetch('https://example.com/path', {method:'GET', 
headers: {'Authorization': 'Basic ' + btoa('login:password')}})
.then(response => response.json())
.then(json => console.log(json));

or with await:

let response = await fetch('https://example.com/path', {method:'GET', 
headers: {'Authorization': 'Basic ' + btoa('login:password')}});
let data = await response.json();
console.log(data);

Solution 5:

If you have a backend server asking for the Basic Auth credentials before the app then this is sufficient, it will re-use that then:

fetch(url, {
  credentials: 'include',
}).then(...);