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:

Kuba Mikita

Kuba Mikita

Share This Article:

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

In today’s online world, your WordPress website isn’t just a spot on the internet. It’s the face of what you do, whether that’s your business, sharing ideas, or showing off...

Are you experiencing challenges with WordPress email notifications not arriving as expected? This is a common problem in the WordPress community, but don’t worry. This guide is specifically designed to...

Engaging users effectively is not just an option; it’s a necessity for survival and growth. WordPress site owners, in particular, often rely on email notifications to keep their audience informed...

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.