New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details →
Socket
Book a DemoSign in
Socket

fetch-json-timeout

Package Overview
Dependencies
Maintainers
1
Versions
15
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

fetch-json-timeout

Use fetch to get JSON data in a timely fashion

latest
Source
npmnpm
Version
8.0.0
Version published
Weekly downloads
4
-33.33%
Maintainers
1
Weekly downloads
 
Created
Source

fetch-json-timeout

A wrapper around the native fetch API for getting JSON data with configurable timeouts, automatic JWT token management, and typed errors.

Installation

npm install fetch-json-timeout

Usage

Basic (no authentication)

import fetchJson from 'fetch-json-timeout';

const fetcher = await fetchJson();
const data = await fetcher('GET', 'https://api.example.com/items');

With Basic Auth

const fetcher = await fetchJson('username', 'password');
const data = await fetcher('GET', 'https://api.example.com/items');

With JWT Authentication

Pass a JWT options object to enable automatic token management. The fetcher will acquire a token on init and transparently refresh it when it nears expiry.

import fetchJson from 'fetch-json-timeout';

const jwtOpts = {
  uri: 'https://api.example.com/auth/login/',
  refreshUri: 'https://api.example.com/auth/refresh/',
  verb: 'POST',
  payload: {
    email: 'user@example.com',
    password: 'your_password'
  }
};

const fetcher = await fetchJson(undefined, undefined, jwtOpts);
const data = await fetcher('GET', 'https://api.example.com/protected/resource');

With a Static Service Token

For long-lived service account tokens that don't expire and don't need refreshing, pass an object with just a token key (no uri):

const fetcher = await fetchJson(undefined, undefined, {
  token: 'my-long-lived-service-token'
});

const data = await fetcher('GET', 'https://api.example.com/internal/resource');

Custom Timeout

The third argument to the fetcher is a timeout in milliseconds (default: 60000). If the request does not complete within this time, a TimeoutError is thrown.

const fetcher = await fetchJson();

// Timeout after 5 seconds
const data = await fetcher('GET', 'https://api.example.com/items', 5000);

POST with Payload

const fetcher = await fetchJson();

const newItem = { name: 'Widget', price: 9.99 };
const data = await fetcher('POST', 'https://api.example.com/items', 60000, undefined, newItem);

Callback Style

An optional callback is invoked with the response data before the promise resolves.

const fetcher = await fetchJson();

fetcher('GET', 'https://api.example.com/items', 60000, data => {
  console.log('Got data:', data);
});

Error Handling

All failures reject with a typed error. Import the error classes to distinguish between failure modes:

import fetchJson, { TimeoutError, HttpError, NetworkError } from 'fetch-json-timeout';

const fetcher = await fetchJson();

try {
  const data = await fetcher('GET', 'https://api.example.com/items', 5000);
} catch (e) {
  if (e instanceof TimeoutError) {
    // Request exceeded the timeout
    console.log(e.timeout); // 5000
  }

  if (e instanceof HttpError) {
    // Server responded with a non-2xx status
    console.log(e.status); // 404, 500, etc.
  }

  if (e instanceof NetworkError) {
    // DNS failure, connection refused, etc.
    console.log(e.cause); // The underlying error
  }
}

Error Properties

Error ClassPropertiesWhen
TimeoutErrortimeout (ms)Request did not complete within the limit
HttpErrorstatus (number)Server returned a non-2xx response code
NetworkErrorcause (Error)Network-level failure (DNS, refused, etc.)

All three extend Error and have a descriptive message string.

API

fetchJson(username?, password?, jwtOpts?)

Returns a Promise<fetcher>.

ParameterTypeDescription
usernamestringUsername for Basic auth (optional)
passwordstringPassword for Basic auth (optional)
jwtOptsobjectJWT configuration object (optional)

jwtOpts shape (JWT with refresh):

KeyTypeDescription
uristringLogin endpoint URL
refreshUristringToken refresh endpoint URL
verbstringHTTP method for auth ("POST")
payloadobjectCredentials to send to login

jwtOpts shape (static service token):

KeyTypeDescription
tokenstringA long-lived bearer token (no expiry or refresh)

fetcher(verb, uri, timeout?, callback?, payload?)

Returns a Promise<data> that resolves with the parsed JSON response.

ParameterTypeDefaultDescription
verbstringHTTP method (GET, POST, PUT, etc.)
uristringRequest URL
timeoutnumber60000Timeout in milliseconds
callbackfunctionno-opCalled with response data
payloadobjectBody for POST/PUT (JSON-serialized)

License

Apache-2.0

Keywords

fetch

FAQs

Package last updated on 24 Jan 2026

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts