2 min read

How to pass query params to a GET request with fetch

Doing a GET request with fetch is easy:

const data = await fetch(`https://pokeapi.co/api/v2/pokemon`)
                .then(reponse => response.json());

But what if you need to pass query string params? E.g. https://pokeapi.co/api/v2/pokemon?limit=100000&offset=0.
How would you write this if you wanted to pass dynamic values for the limit or offset?

You can use the URL and URLSearchParams browser APIs:

const url = new URL('https://pokeapi.co/api/v2/pokemon');
const params = { limit: "100000", offset: "0" }
url.search = new URLSearchParams(params).toString();

const data = await fetch(url).then(reponse => response.json());

And that's it!

Looking for a shorter version?

You can just concatenate the params and toString will be called for you behind the scenes:

const params = new URLSearchParams({ limit: "100000", offset: "0" });
fetch(`https://pokeapi.co/api/v2/pokemon?${params}`);

Wondering why you can't just concatenate the params?

What is wrong with just concatenating the limit and offset using template strings?

const limit = "100", offset = 10;
fetch(`https://pokeapi.co/api/v2/pokemon?limit=${limit}&offset=${offset}`);

This works in this case, but you're not encoding the values, so you might run into unexepected behaviour if the user inputs special characters. For example, the # is considered a special characters that marks the end of the query string. If your user "hacks" the query params and passes "100#" as the limit value, your offset will be ignored!

If you want to try this out for yourself, go to https://pokeapi.co/ and try out the requests in the Chrome DevTools Console.

To fix this, you need to encode the query parameters before passing them - which you can do with the encodeURIComponent function:

As you can see, manually encoding every query parameter is quite tedious, which is why URLSearchParams API is a nicer solution!

Get the React Practice Calendar!

28 days of focused practice of increasing difficulty, going through everything from Fundamentals, Data fetching, Forms and using Intervals in React.

You will also get notified whenever a new challenge is published.