Fetch API in Vanilla JavaScript

— 3 minute read


I remember back in the days of jQuery $.ajax was a big, big thing. But nowadays we have fetch a way cooler, faster and more awesome solution. The best part; it works in Vanilla JavaScript!

How to make a get request with Fetch permalink


That is as basic as it gets, won't do much since we are not returning any data.

Returning json data with Fetch permalink

.then(function(response) {
// Successfull fetch return as json
return response.json();
.then(function(data) {
// Data now contains the json
.catch(function(error) {
// A Error occured

Fetch works on promises, so we can return a promise chain as we learned on 20-03-2020: Promise chains in JavaScript.

The first response will return an object, not an actual response, so we need to tell the promise chain that we want to return this response as JSON.

You can play around with this codepen.

See the Pen Fetch API in Vanilla JavaScript by Chris Bongers (@rebelchris) on CodePen.

Browser support permalink

Fetch has excellent support, but not in IE. 😓

You can use a polyfill for this.

Fetch browser support

Thank you for reading, and let's connect! permalink

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter