Setting query string using Fetch GET request

A concise, modern approach:

fetch('https://example.com?' + new URLSearchParams({
    foo: 'value',
    bar: 2,
}))

How it works: When a string (e.g. the URL) is being concatenated with an instance of URLSearchParams, its toString() method will automatically be called to convert the instance into a string representation, which happens to be a properly encoded query string. If the automatic invoking of toString() is too magical for your liking, you may prefer to explicitly call it like so: fetch('https://...' + new URLSearchParams(...).toString())

A complete example of a fetch request with query parameters:

// Real example you can copy-paste and play with.
// jsonplaceholder.typicode.com provides a dummy rest-api
// for this sort of purpose.
async function doAsyncTask() {
  const url = (
    'https://jsonplaceholder.typicode.com/comments?' +
    new URLSearchParams({ postId: 1 }).toString()
  );

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

  console.log('Fetched from: ' + url);
  console.log(result);
}

doAsyncTask();

If you are using/supporting…

  • IE: Internet Explorer does not provide native support for URLSearchParams or fetch, but there are polyfills available.

  • Node: As of Node 18 there is native support for the fetch API (in version 17.5 it was behind the --experimental-fetch flag). In older versions, you can add the fetch API through a package like node-fetch. URLSearchParams comes with Node, and can be found as a global object since version 10. In older version you can find it at require('url').URLSearchParams.

  • Node + TypeScript: If you’re using Node and TypeScript together you’ll find that, due to some technical limitations, TypeScript does not offer type definitions for the global URLSearchParams. The simplest workaround is to just import it from the url module. See here for more info.

Leave a Comment