Explain Codes LogoExplain Codes Logo

Basic authentication with fetch?

javascript
fetch-api
basic-authentication
browser-nodejs
Alex KataevbyAlex Kataev·Jan 30, 2025
TLDR

To conduct basic authentication using fetch, set an Authorization header as follows: Basic + btoa(username + ':' + password). Here's a no-nonsense, compact code snippet:

// Surprise batman with your 'Basic' auth weapon! const auth = btoa('BruceWayne:ImBatman'); fetch('https://gotham.api/endpoint', { headers: { 'Authorization': `Basic ${auth}` } }) .then(res => res.json()) // Ah, sweet JSON... .then(console.log) .catch(console.error); // error's identity has been unmasked here!

Horses for courses: Browser & Node.js

When executing basic authentication in JavaScript, btoa is your loyal sidekick in the browser environment. But for Node.js, you can count on Buffer.from() to deliver the Base64-encoded secret code!

// For Node.js const auth = Buffer.from('BruceWayne:ImBatman').toString('base64'); // Buffer is a friend of Node.js // For browsers const auth = btoa('BruceWayne:ImBatman'); // btoa: beloved by browsers!

Digging deeper with credentials

The overlooked hero in our story is the credentials option in fetch. If our mission is to infiltrate an endpoint on a different origin, we must set the credentials option to include to ensure our cookies or session data gets across the border!

fetch('https://gotham.api/endpoint', { credentials: 'include', // Our secret pass to different origins! headers: { 'Authorization': `Basic ${auth}` }, // And of course, our key! }) // .then() and .catch() adventures continue here.

Sharpshooting: Error handling & debugging

Handling errors is like Batman's needs to counter villain attacks! Status of the response should be checked and different scenarios should be handled like a true caped crusader :

fetch('https://gotham.api/endpoint', { headers: { 'Authorization': `Basic ${auth}` }, // basic auth, away we go! }) .then(response => { if (!response.ok) throw new Error('Oh no! Gotham is under attack!'); // When villains attack, we respond! return response.json(); // Safe and sound, back to Wayne Manor. }) .then(data => {/* Process your data like Alfred processes Bruce's mails! */}) .catch(error => console.error('Batignal!', error));

Be on your guard for small enemies like misspellings or syntax errors. These tiny villains can wreak havoc with your fetch request!

Advanced tactics: strings, headers & server demands

Handling non-ASCII characters

You are the silent guardian of internationalization dealing with special characters! Use unibtoa or a polyfill to encode UTF-8 characters properly:

function unibtoa(s) { return btoa(unescape(encodeURIComponent(s))); } const auth = unibtoa('Batman:Batcave123'); // solves the Riddler's puzzle!

Stepping up to server's demands

Brush up on your detective skills and confirm your server's requirements, they might be demanding digest authentication or using additional tokens!

Understanding HTTP Headers

Good job, Alfred. Now let's organize this bat-utility belt, the Headers object, for managing headers dynamically!

const headers = new Headers(); headers.set('Authorization', 'Basic ' + btoa('Batman:Batcave123')); // suit up, Bats! fetch('https://gotham.api/endpoint', { headers }) // .then() and .catch() — Batman's back in action!