Skip to content


Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Latest commit


Git stats


Failed to load latest commit information.
Latest commit message
Commit time



A wrapper around Fetch just for JSON

License:MIT npm Size Vulnerabilities Build

Why would you fetch anything but json? ;)

A) Make REST Easy

fetch-json is a lightweight JavaScript library to reduce the boilerplate code needed to make HTTP calls to JSON endpoints.

fetch-json automatically:

  1. Adds the HTTP header Content-Type: application/json to ensure the correct data type
  2. Serializes the body payload with JSON.stringify()
  3. Runs .json() on the response
  4. Appends params to the URL of GET requests
  5. Sets credentials to 'same-origin' (support user sessions in Grails, Rails, PHP, Django, Flask, etc.)
  6. Converts the HTTP response to JSON if it's not already JSON (especially convenient for HTTP errors)
  7. Maps HTTP response headers from a HEAD request into a simple object

fetch-json is ideal for a JAMstack architecture where "dynamic programming during the request/response cycle is handled by JavaScript, running entirely on the client".

B) Setup

1. Web browser

In a web page:

<script src=fetch-json.min.js></script>

or from the CDN:

<script src=></script>

2. Node.js server

Install package for node:

$ npm install fetch-json

and then import:

import { fetchJson } from 'fetch-json';

or for older CommonJS modules use:

const { fetchJson } = require('fetch-json');  //deprecated -- use ES modules instead

Requires minimum node v18.

If you use GitHub Actions, ensure the version of node is set correclty:

- uses: actions/setup-node@v3
    node-version: 18

C) Examples


Fetch the NASA Astronomy Picture of the Day:

const url =    '';
const params = { api_key: 'DEMO_KEY' };
const handleData = (data) =>
   console.log('The NASA APoD for today is at:', data.url);
fetchJson.get(url, params).then(handleData);

Example output:

> The NASA APoD for today is at:


Create a resource for the planet Jupiter:

// Create Jupiter
const resource = { name: 'Jupiter', position: 5 };
const handleData = (data) =>
   console.log('New planet:', data);  //http response body as an object literal'', resource)

For more examples, see the Mocha specification suite:
spec/node.spec.js (Mocha output for each build under Run npm test)

To see a website that incorporates fetch-json, check out DataDashboard: πŸ“Š

D) Examples Using async/await


Fetch the NASA Astronomy Picture of the Day:

const show = async () => {
   const url =    '';
   const params = { api_key: 'DEMO_KEY' };
   const data =   await fetchJson.get(url, params);
   console.log('The NASA APoD for today is at: ' + data.url);


Create a resource for the planet Jupiter:

// Create Jupiter
const create = async (resource) => {
   const data = await'', resource);
   console.log('New planet:', data);  //http response body as an object literal
create({ name: 'Jupiter', position: 5 });

E) Leverages Fetch API

fetch-json calls the native Fetch API.

For comparison, the POST example in section C) Examples to create a planet would be done calling the Fetch API directly with the code:

// Create Jupiter (WITHOUT fetch-json)
const resource = { name: 'Jupiter', position: 5 };
const options = {
   method: 'POST',
   headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
   body: JSON.stringify(resource),
const handleData = (data) =>
   console.log(data);  //http response body as an object literal
fetch('', options)
   .then(response => response.json())

The example with fetch-json and the example without fetch-json each produce the same output.


1. API β€” HTTP Request

The format for using fetch-json is:


fetchJson.get(url, params, options).then(callback);

POST, resource, options).then(callback);


fetchJson.put(url, resource, options).then(callback);


fetchJson.patch(url, resource, options).then(callback);


fetchJson.delete(url, resource, options).then(callback);

HEAD (HTTP response headers)

fetchJson.head(url, params, options).then(callback);  //headers returned as an object


  1. Only the url parameter is required.Β  The other parameters are optional.
  2. The params object for fetchJson.get() is converted into a query string and appended to the url.
  3. The resource object is turned into the body of the HTTP request.
  4. The options parameter is passed through to the Fetch API (see the init documentation on MDN).
  5. options is enhanced with a boolean setting for strictErrors mode (default false) that throws an error to .catch() whenever the HTTP response status is 400 or higher.

Dynamic HTTP method

If you need to programmatically set the method, use the format:

fetchJson.request(method, url, data, options).then(callback);

Where method is 'GET', 'POST', 'PUT', 'PATCH', or 'DELETE', and data represents either params or resource.

2. API β€” logging

Enable basic logging to the console with:


To use a custom logger, pass in a function that accepts 9 parameters to log. To disable logging, pass in false.

To get an array containing the names of the parameters:


The default console output looks like:
2018-09-12T07:20:12.372Z – "request" - "GET" – "" – ""
2018-09-12T07:20:13.009Z – "response" - "GET" – "" – "" - true - 200 - "OK" - "application/json"

G) Response Text Converted to JSON

The HTTP response body is considered to be JSON if the Content-Type is "application/json" or "text/javascript".Β  If the HTTP response body is not JSON, fetch-json passes back through the promise an object with a bodyText string field containing response body text.

In addition to the bodyText field, the object will have the fields: ok, status, statusText, and contentType.

For example, an HTTP response for an error status of 500 would be converted to an object similar to:

   ok:          false,
   status:      500,
   statusText:  'INTERNAL SERVER ERROR',
   contentType: 'text/html; charset=utf-8',
   bodyText:    '<!doctype html><html lang=en><body>Server Error</body></html>',

With fetch-json, you know the response body will always be passed back to you as a simple object literal.

H) Base Options

Use fetchJson.setBaseOptions() to configure options to be used on future fetchJson requests.

The example below sets the Authorization HTTP header so it is sent on the subsequent GET and DELETE requests:

fetchJson.setBaseOptions({ headers: { Authorization: 'Basic WE1MIGlzIGhpZGVvdXM=' } });
fetchJson.get('').then(display);  //with auth header
fetchJson.delete('');           //with auth header

To have multiple base options available at the same time, use the FetchJson class to instantiate multiple copies of fetchJson:

import { FetchJson } from 'fetch-json';

const fetchJsonA = new FetchJson({ headers: { From: '' } }).fetchJson;
const fetchJsonB = new FetchJson({ headers: { From: '' } }).fetchJson;
fetchJsonA.get('').then(display);  //from
fetchJsonB.delete('');           //from

I) TypeScript Declarations

See the TypeScript declarations at the top of the fetch-json.ts file.

The declarations provide type information about the API. For example, the function returns a Promise for a FetchResponse: string, resource?: RequestData,
   options?: FetchOptions): Promise<FetchResponse>

J) Fetch polyfills

1. Add Fetch to JSDOM

JSDOM does not include fetch, so you need to add a polyfill.

$ npm install --save-dev whatwg-fetch

See usage of whatwg-fetch in spec/jsdom.spec.js.

2. Legacy Node.js

Native support for Fetch API was introduced in node v18 which became the Active LTS version on 2022-10-25.Β  If you're using an older version of node, stick with fetch-json v2.7 and in your package.json file declare a dependency on the node-fetch polyfill package.

$ npm install node-fetch

3. Legacy web browsers

To support really old browsers, include polyfills for Promise and Fetch API:

<script src=></script>
<script src=></script>

"Stop trying to make fetch happen without #fetchJson!"

Feel free to submit questions at:

MIT License