DEV Community

Kevin Sassé
Kevin Sassé

Posted on

A beginner's attempt at fetch() and a crash-course on browser cache

Backstory: You changed your employment status to part-time so you can attend a full-time coding bootcamp. You spent a few weeks prior to the first day of class slowly going through the pre-course material just learning the basics like; "what even is a function?". All the while doing your best to make sure you don't overlook a topic.

Three weeks ago, the bootcamp started. On day one, you're suddenly thrown into content overload. Gone is the slow methodical pace you had during the pre-course work. Someone just strapped a brick on the gas pedal, the bootcamp is moving along at full speed. You stumbled a bit on the first day trying to keep up but quickly found a rhythm.

Today: Now here you are, three weeks later working on the end of phase project. A month ago you didn't even know what the DOM was and in a few days you will have completed your first single page application that uses an API and next week will be learning React.

You could've kept things easier for self and created a db.json and used a json server to host it, but you wanted a challenge. You did the local server and db.json thing, and used an external public API for source data. You are feeling confident that you can handle two different APIs within this project and start coding.

You make your html, css & js files, link them up and everything seems to be working locally. You remembered a tip from your instructor:

Set your endpoints to variables so you only have to change it one place if it ever changes.

With that in mind, you write out the fetch request:

fetch(externalUrl)
.then(res => res.json())
.then(data => console.log(data)
Enter fullscreen mode Exit fullscreen mode

This endpoint is supposed to pull a random object from the database. Satisfied that it looks like what you saw in the lectures and labs, you open up the html file in a browser and hope you see some data...

SUCCESS! You did it! An object appeared in your console from an external source! Three weeks ago those three lines of code meant absolutely nothing to you and now you can write code to communicate with a server!

Image description

You quickly add a button to your webpage to call this API and get a new object every time it is clicked and refresh the web page. You start clicking, seeing a new entry in the console log every time. It works!

And then you see it. You actually read the logged information. Its the same object. Every. Single. Time... Why? How? You scratch your head for a while trying to figure out what is happening. The API docs provided a demo of this endpoint and it returned a different object every time, why isn't that happening in your code?

You try different browsers, you ask other students to try making a request to that endpoint on their machines, but the end result is always the same. Enter:

Browser Cache

All browsers have a cache, most apps on your smart devices have one as well. Your device's CPU even has built-in layers of cache. What is it?

The cache is a high-speed read/write storage layer used to hold commonly accessed data.

It is commonly used to help make a smoother user experience by reducing loading times. Instead of having to constantly make new requests to the same endpoint, the browser will cache the initial response, then reference the cache if the request is going to the same endpoint with the same parameters. It makes the assumption it will receive the same response in that scenario and will return the cached information instead.

In your project, since the button is sending a request to the same endpoint without changing any parameters to get a new random object, the browser's network tab will show that the request targeted the cache instead because nothing about the request changed, however, it should have been a different response:

Image description

By default, when a request is made using the javascript fetch API, the cache header used is "default". Meaning:

"default": Fetch will inspect the HTTP cache on the way to the network. If there is a fresh response it will be used. If there is a stale response a conditional request will be created, and a normal request otherwise. It then updates the HTTP cache with the response.

This is why every time you click that button to pull a random object, your browser is instead, retrieving the cached object from your initial request.

While caching does make using the internet and many programs smoother and provide a better user experience, there may be cases in which you want to disable it. Say, for instance, your end of phase project where you want a different random object on every time. Fortunately for you, there is a simple solution to force a request to skip the cache and get a new a new response instead.

cache: "no-cache"

Setting the HTTP header cache: to the value "no-cache" in your fetch request will tell the browser to store the response in the cache after it is re-validated. This means you should get a fresh response each time you click the button and get a new random object.

fetch(externalUrl,{
      cache: "no-cache"
})
.then(res => res.json())
.then(data => console.log(data)
Enter fullscreen mode Exit fullscreen mode

You then reload the webpage and click the button a few times to test it:

Image description

You did it! The request is getting a server response every time! Your first hurdle of the project is resolved. You know it won't be long before the next one shows up, but that doesn't slow you down. You signed up for this bootcamp to learn, and hurdles a good learning experiences.

For further reading:
https://javascript.info/fetch-api
https://www.openbrewerydb.org/documentation
https://stackoverflow.com/questions/31601167/fetch-api-cache-mode

Top comments (0)