# fetch-json-timeout

> Use fetch to get JSON data in a timely fashion

Latest version **8.0.0** (published 2026-01-24) · Apache-2.0 license · 0 weekly downloads

## Install

```sh
npm install fetch-json-timeout
pnpm add fetch-json-timeout
yarn add fetch-json-timeout
bun add fetch-json-timeout
```

## Health

**Score 50/100 (C)** — status: stable.

Positive: esm support; no vulnerabilities.

Warnings: low downloads; no types.

## Facts

| | |
|---|---|
| Version | 8.0.0 |
| Published | 2026-01-24 |
| First published | 2018-04-06 |
| Weekly downloads | 0 |
| License | Apache-2.0 |
| TypeScript types | none |
| Module format | ESM + CommonJS |
| Dependencies | 2 |
| Unpacked size | 16.8 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 0 |
| Author | Jan Badenhorst |
| Maintainers | gumm |
| Keywords | fetch, json, timeout |

## Links

- npm: https://www.npmjs.com/package/fetch-json-timeout
- Repository: https://github.com/gumm/fetch-json-timeout
- Homepage: https://github.com/gumm/fetch-json-timeout#readme
- Issues: https://github.com/gumm/fetch-json-timeout/issues
- npm.io page: https://npm.io/package/fetch-json-timeout

## Dependencies (2)

- [base-64](https://npm.io/package/base-64.md) ^1.0.0
- [timeout-signal](https://npm.io/package/timeout-signal.md) ^2.0.0

## Alternatives

- [@mapbox/jsonlint-lines-primitives](https://npm.io/package/@mapbox/jsonlint-lines-primitives.md) — 5.3M weekly downloads
- [reftools](https://npm.io/package/reftools.md) — 3.5M weekly downloads
- [@hey-api/openapi-ts](https://npm.io/package/@hey-api/openapi-ts.md) — 3.5M weekly downloads
- [@mapbox/geojson-rewind](https://npm.io/package/@mapbox/geojson-rewind.md) — 2.4M weekly downloads
- [turbo-stream](https://npm.io/package/turbo-stream.md) — 1.7M weekly downloads

## Recent versions

- 8.0.0 (latest) — 2026-01-24
- 7.0.0 — 2023-03-05
- 6.0.0 — 2023-03-05
- 5.0.0 — 2023-02-27
- 4.0.3 — 2022-02-24
- 4.0.2 — 2022-02-24
- 4.0.1 — 2022-02-24
- 4.0.0 — 2022-02-24
- 3.0.1 — 2021-05-25
- 3.0.0 — 2021-05-24
- 2.0.0 — 2021-05-03
- 1.2.2 — 2018-10-31
- 1.2.0 — 2018-10-31
- 1.0.1 — 2018-04-06
- 0.0.1 — 2018-04-06

## README

# 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

```bash
npm install fetch-json-timeout
```

## Usage

### Basic (no authentication)

```javascript
import fetchJson from 'fetch-json-timeout';

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

### With Basic Auth

```javascript
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.

```javascript
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`):

```javascript
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.

```javascript
const fetcher = await fetchJson();

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

### POST with Payload

```javascript
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.

```javascript
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:

```javascript
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 Class    | Properties           | When                                      |
|----------------|----------------------|-------------------------------------------|
| `TimeoutError` | `timeout` (ms)       | Request did not complete within the limit  |
| `HttpError`    | `status` (number)    | Server returned a non-2xx response code    |
| `NetworkError` | `cause` (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>`.

| Parameter  | Type     | Description                          |
|------------|----------|--------------------------------------|
| `username` | `string` | Username for Basic auth (optional)   |
| `password` | `string` | Password for Basic auth (optional)   |
| `jwtOpts`  | `object` | JWT configuration object (optional)  |

**`jwtOpts` shape (JWT with refresh):**

| Key          | Type     | Description                        |
|--------------|----------|------------------------------------|
| `uri`        | `string` | Login endpoint URL                 |
| `refreshUri` | `string` | Token refresh endpoint URL         |
| `verb`       | `string` | HTTP method for auth (`"POST"`)    |
| `payload`    | `object` | Credentials to send to login       |

**`jwtOpts` shape (static service token):**

| Key     | Type     | Description                                      |
|---------|----------|--------------------------------------------------|
| `token` | `string` | A 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.

| Parameter  | Type       | Default | Description                            |
|------------|------------|---------|----------------------------------------|
| `verb`     | `string`   |         | HTTP method (`GET`, `POST`, `PUT`, etc.) |
| `uri`      | `string`   |         | Request URL                            |
| `timeout`  | `number`   | `60000` | Timeout in milliseconds                |
| `callback` | `function` | no-op   | Called with response data              |
| `payload`  | `object`   |         | Body for POST/PUT (JSON-serialized)    |

## License

Apache-2.0

---
_Source: https://npm.io/package/fetch-json-timeout · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
