JavaScript Fetch with Basic Auth

Sometimes it is necessary to use fetch from a server secured with basic auth (very often in case of staging domains), usually, the authorization is done by login and password included within the URL itself:

user:pass@domain.com 

JavaScript may seem pretty obvious:

const result = await fetch(`user:pass@domain.com/${endpoint}`, {
    method: 'POST',
    body: content,
    headers: {
        'Content-Type': 'application/json',
    },
});

But in case of fetch this is not allowed and will result in an error:

TypeError: Failed to execute 'fetch' on 'Window': Request cannot be constructed from a URL that includes credentials: https://user:pass@domain.com   

To make it work, get rid of the login and password and add them to the fetch with:

const result = await fetch(`domain.com/${endpoint}`, {
    method: 'POST',
    body: content,
    headers: {
        'Content-Type': 'application/json',
        'Authorization': `Basic ${btoa('user:pass')}`,
    },
});

Your email address will not be published.