HTTP Basic Authentication sends credentials as a Base64-encoded string in the
Authorization header. The format is Basic base64(username:password).
While simple to implement, Basic Auth should only be used over HTTPS since the
credentials are easily decoded (Base64 is encoding, not encryption).
Creating the Authorization Header
function createBasicAuthHeader(username, password) {
const credentials = `${username}:${password}`;
const encoded = btoa(credentials);
return `Basic ${encoded}`;
}
createBasicAuthHeader('alice', 'secret123');
btoa() encodes a string to Base64 in the browser.
The result is NOT encrypted — anyone can decode it with atob().
Making Authenticated Requests
async function fetchWithBasicAuth(url, username, password) {
const response = await fetch(url, {
headers: {
'Authorization': createBasicAuthHeader(username, password)
}
});
if (response.status === 401) {
throw new Error('Invalid credentials');
}
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return response.json();
}
try {
const data = await fetchWithBasicAuth(
'https://api.example.com/protected',
'myuser',
'mypassword'
);
} catch (error) {
console.error('Auth failed:', error.message);
}
Handling Unicode Characters
function createBasicAuthHeaderUnicode(username, password) {
const credentials = `${username}:${password}`;
const encoder = new TextEncoder();
const bytes = encoder.encode(credentials);
const binary = String.fromCharCode(...bytes);
const encoded = btoa(binary);
return `Basic ${encoded}`;
}
createBasicAuthHeaderUnicode('user', 'pässwörd');
Try It Live
Input
Enter credentials above
Authorization Header
Security Warning
- Basic Auth sends credentials with every request
- Base64 is NOT encryption — credentials are easily decoded
- ALWAYS use HTTPS with Basic Auth
- Consider using tokens (Bearer auth) for better security
- Never store passwords in JavaScript code
← Back to HTTP Examples