Skip to content
Swizec Teller - a geek with a hatswizec.com

A tiny ES6 fetch() wrapper that makes your life easier

After yesterday's shenanigans with ES6 fetch(), I made a tiny library called better-fetch which makes your life easier. Or at least it makes my life easier.

Without changing the API, better-fetch automatically includes cookies, which would have saved me a very frustrating amount of time yesterday, lets you add default headers, and you can pass request body as a plain JS object. None of that FormData nonsense.

better-fetch works the same as fetch(), but is less cumbersome to use.

In practice, better-fetch looks like this:

You install with npm. Or whatever you use to install packages from npmjs.org. Yarn maybe?

$ npm install --save better-fetch

Then you set up headers that every one of your fetch() calls needs. My backend requires an Authorization and an Accept header from all calls.

// top of project
// src/index.js
import fetch from "better-fetch";
fetch.setDefaultHeaders({
Authorization: `Token token=${GlobalTokenValue}`,
Accept: "application/json.v2",
});
// ^ this is optional and depends on your use-case ^

You can then use better-fetch anywhere in your code as you normally would with fetch(). The API feels the same and promises to work just like you'd expect.

// any file
import fetch from "better-fetch";
fetch("/api/some/thing")
.then((response) => response.json())
.then((json) => {
// do stuff
});

This code fetches JSON document with a GET request to the /api/some/thing URL. Any default headers are set in the request and cookies are sent as well.

POST-ing is also made less cumbersome:

// any file
import fetch from "better-fetch";
const data = {
key: "value",
key2: "value2",
};
fetch("/api/save_response", { method: "POST", body: data })
.then((response) => response.json())
.then((json) => {
console.log(json);
});

A dictionary body is automatically transformed into a FormData object, and strings and FormData objects are let through. This gives you flexibility to work with any API backend, but it still makes your life easier.

Similarly, you can specify headers as either a Headers object or a dictionary – better-fetch has you covered.

Happy hacking ?

PS: I know a bunch of fetch wrappers exist already. They all make significant changes to the API, and I wanted to avoid that.

Did you enjoy this article?

Published on November 2nd, 2016 in Front End, react, Technical

Learned something new?
Want to become a high value JavaScript expert?

Here's how it works 👇

Leave your email and I'll send you an Interactive Modern JavaScript Cheatsheet 📖right away. After that you'll get thoughtfully written emails every week about React, JavaScript, and your career. Lessons learned over my 20 years in the industry working with companies ranging from tiny startups to Fortune5 behemoths.

Start with an interactive cheatsheet 📖

Then get thoughtful letters 💌 on mindsets, tactics, and technical skills for your career.

"Man, love your simple writing! Yours is the only email I open from marketers and only blog that I give a fuck to read & scroll till the end. And wow always take away lessons with me. Inspiring! And very relatable. 👌"

~ Ashish Kumar

Join over 10,000 engineers just like you already improving their careers with my letters, workshops, courses, and talks. ✌️

Have a burning question that you think I can answer? I don't have all of the answers, but I have some! Hit me up on twitter or book a 30min ama for in-depth help.

Ready to Stop copy pasting D3 examples and create data visualizations of your own?  Learn how to build scalable dataviz components your whole team can understand with React for Data Visualization

Curious about Serverless and the modern backend? Check out Serverless Handbook, modern backend for the frontend engineer.

Ready to learn how it all fits together and build a modern webapp from scratch? Learn how to launch a webapp and make your first 💰 on the side with ServerlessReact.Dev

Want to brush up on your modern JavaScript syntax? Check out my interactive cheatsheet: es6cheatsheet.com

By the way, just in case no one has told you it yet today: I love and appreciate you for who you are ❤️