fbpx
Search
Close this search box.

Home / Blog

 / 
JavaScript Fetch with Basic Auth

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:[email protected] 

JavaScript may seem pretty obvious:

const result = await fetch(`user:[email protected]/${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:[email protected]   

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')}`,
    },
});

Share This Article:

Picture of Kuba Mikita

Kuba Mikita

Share This Article:

Picture of Kuba Mikita

Kuba Mikita

Share This Article:

Latest updates, discounts and more!

Get the most recent updates on WordPress automation, fresh plugins, new features and price cuts.

Related articles

Today, I'll talk about this exact topic. We'll compare two popular methods for constructing websites: the page builder - Elementor, and Full Site Editing (FSE) using Gutenberg blocks....

Recently, we came across a problem, while developing a new version of the Notification plugin. We wanted to tidy up our codebase and one of the tasks was to rename...

Following the success of the Notification plugin, we knew that personalization was the direction we would pursue. Thanks to feedback, we were easily able to identify the needs of the...

WordPress Plugins that get the job done

With years of experience creating client websites, we bring our experience to functional WordPress plugins.

Easy to use for everyone

Regardless of experience level, you can easily use our products.

Top-notch Support included

We treat our clients seriously and focus heavily on support. Reviews backs this up!

Extensible and developer friendly

You're the same developer as we are. Our code is clean and extensible, just the way you like.