How to Send Basic Auth with JavaScript fetch()
Construct a Basic Authorization header for fetch and troubleshoot Unicode encoding, CORS, and exposed credentials.

fetch() accepts an Authorization header through its headers option. The tricky parts are generating the correct bytes, handling cross-origin requests, and deciding whether a browser should possess the credentials at all. Use a local test account when learning the request format.
Encode UTF-8 bytes before Base64
Calling btoa directly on arbitrary Unicode text can throw or encode the wrong bytes. Use TextEncoder to turn the credential string into UTF-8 bytes, convert those bytes to a binary string, then apply btoa. The server must expect that encoding. Validate the username for colons and reject control characters before constructing the request. The generated header should be treated as sensitive output.
Understand browser CORS behavior
For a cross-origin request, an explicit Authorization header normally triggers a preflight. The API must allow your origin, requested method, and Authorization header. A browser CORS error cannot be fixed by changing Base64 or adding access-control response headers to the client request. Inspect the OPTIONS response and configure the API. The credentials option controls browser-managed credentials such as cookies; it does not create a Basic header for you.
Keep shared service secrets on the server
A credential embedded in frontend source or a public build variable is available to users of that application. If the integration uses a shared service account, make the authenticated request through a trusted backend with appropriate authorization. When handling an end user’s own credentials, minimize retention and avoid logging the header. Check response.ok and handle 401 or 403 deliberately rather than assuming a resolved fetch promise means authentication succeeded.
Worked example
const bytes = new TextEncoder().encode(`${username}:${password}`);
let binary = "";
for (const byte of bytes) binary += String.fromCharCode(byte);
const response = await fetch(url, {
headers: { Authorization: `Basic ${btoa(binary)}` }
});Does credentials: include automatically send my username and password?
No. It controls browser-managed credentials. Construct the Authorization header explicitly when that is the API contract.


