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!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

TLDR – QUICK SLIDES

Fullscreen Mode – Click Here

 

TABLE OF CONTENTS

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

  • Captain Obvious – Use http:// to access fetch.html, not file://.
  • Take note, the protected/ folder will only work with Apache.
  • The credentials for protected/ is USER and PASS.
If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

 

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.

 

 

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!

Leave a Comment

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