Javascript Fetch With HTTP Basic Auth (Simple Example)

Welcome to a tutorial and example on how to do a Javascript Fetch request with HTTP basic auth.

To perform Fetch with HTTP basic auth, simply include the authorization headers in the request.

  • var credentials = btoa("USER:PASSWORD");
  • var auth = { "Authorization" : `Basic ${credentials}` };
  • fetch("http://site.com/protected/", { headers : auth });

That covers the quick basics, but read on for a detailed example!

 

 

TLDR – QUICK SLIDES

[web_stories_embed url=”https://code-boxx.com/web-stories/javascript-fetch-with-http-basic-auth/” title=”Javascript Fetch With HTTP Basic Auth” poster=”https://code-boxx.com/wp-content/uploads/2021/11/STORY-JS-20230518.webp” width=”360″ height=”600″ align=”center”]

Fullscreen Mode – Click Here

 

TABLE OF CONTENTS

 

 

FETCH BASIC AUTH

All right, let us now get into the example of doing HTTP basic auth with Javascript fetch.

 

FETCH WITH HTTP AUTH

fetch.html
<script>
function fetchAuth () {
  // (A) URL & CREDENTIALS
  var url = "protected/secret.html",
      credentials = btoa("USER:PASS");
 
  // (B) FETCH WITH HTTP AUTH
  fetch (url, {
    headers: { "Authorization": `Basic ${credentials}` }
  })
 
  // (C) SERVER RESPONSE
  .then(res => {
    if (res.status != 200) { throw new Error("Bad Server Response"); }
    return res.text();
  })
  .then(res => document.getElementById("demo").innerHTML = res)
 
  // (D) HANDLE ERRORS (OPTIONAL)
  .catch(err => console.error(err));
}
</script>
 
<div id="demo"></div>
<input type="button" value="Fetch Auth" onclick="fetchAuth()">

That’s right, this is pretty much the full version of the introduction snippet.

  1. The target URL and user/password.
  2. As in the introduction, just set the Authorization headers and add the credentials.
  3. Handle the server response. Important note for the newbies – fetch() will consider it a success as long as the server responds. That is, even when the user/password is wrong and it responds with a 403 (unauthorized). Take extra care to do a manual 200 (OK) check here.
  4. Lastly, handle any errors. This is optional but highly recommended.

 

 

EXTRA – BASIC AUTH WITH APACHE

This is a small extra for you guys who are using Apache Web Server. To create a protected folder, simply create a .htaccess file inside.

protected/.htaccess
AuthType Basic
AuthName "Password Required"
AuthUserFile PATH\FOLDER\.htpasswd
Require valid-user

Then, generate your own user/password by running htpasswd in the command line – htpasswd -c "PATH/FOLDER/.htpasswd" USER. If htpasswd is somehow not installed on your server, just search for “htpasswd generator” and use an online generator.

protected/.htpasswd
USER:$apr1$i.0uy9VI$RIL6cpq41G1BEEzsdtY/y0

P.S. It is better to put the .htpasswd somewhere safe, outside of the public HTTP folder.

 

 

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

EXAMPLE CODE DOWNLOAD

Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

EXTRA BITS & LINKS

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

 

LINKS & REFERENCES

 

INFOGRAPHIC CHEAT SHEET

Javascript Fetch WIth Basic Auth (Click To Enlarge)

 

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

1 thought on “Javascript Fetch With HTTP Basic Auth (Simple Example)”

  1. Thanks, that’s all I needed this implementation in my fetch, thanks so much.
    “`js
    var credentials = btoa(“USER:PASSWORD”);
    var auth = { “Authorization” : `Basic ${credentials}` };
    “`

Leave a Comment

Your email address will not be published. Required fields are marked *