npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@andreyvalenko/next-fetch

v2.0.0

Published

Lightweight, typed fetch client for Next.js with interceptors, query params and timeouts

Downloads

297

Readme

next-fetch

A lightweight, fully typed wrapper around the native fetch, built for Next.js.

  • nextFetch() factory with a shared baseURL, headers and cache config
  • ✅ Nested query params (objects, arrays, Date) with correct encoding
  • ✅ Automatic JSON encoding — and raw pass-through for FormData, Blob, streams, typed arrays
  • ✅ Request/response interceptors
  • ✅ Per-request and per-instance timeouts (TimeoutError)
  • ✅ Rich errors (HttpError with status, body, headers)
  • ✅ Next.js fetch options: next.revalidate, next.tags, cache
  • ✅ Ships both ESM and CommonJS builds with type declarations

📦 Installation

npm install @andreyvalenko/next-fetch

Requires Node 18+ (or any runtime with a global fetch).

Usage

1. Create an instance

import { nextFetch } from "@andreyvalenko/next-fetch";

export const api = nextFetch({
  baseURL: "https://api.example.com",
  headers: { "X-App": "web" },
  timeout: 10_000, // ms, optional
});

nextFetch.create({ ... }) is an alias, and new NextFetchClient({ ... }) works too. baseURL is optional — without it, pass absolute urls.

2. GET

type User = { id: number; name: string };

const users = await api.get<User[]>("/users", {
  params: { role: "admin", filter: { tags: ["new", "active"] } },
  next: { revalidate: 60, tags: ["users"] }, // Next.js options
});
// GET /users?role=admin&filter[tags][0]=new&filter[tags][1]=active

3. POST / PUT / PATCH

The body is the second argument; config is the third.

type LoginResponse = { token: string };
type LoginPayload = { email: string; password: string };

const { token } = await api.post<LoginResponse, LoginPayload>("/auth/login", {
  email: "[email protected]",
  password: "123456",
});

FormData, URLSearchParams, Blob, ArrayBuffer, typed arrays and ReadableStream are sent as-is and content-typed by the runtime; everything else is JSON.stringify-ed with Content-Type: application/json.

4. DELETE / HEAD / OPTIONS

await api.delete<void>("/users/1");
await api.delete<void>("/users", { body: { ids: [1, 2] } }); // body allowed

5. Errors

import { HttpError, TimeoutError } from "@andreyvalenko/next-fetch";

try {
  await api.get("/users");
} catch (error) {
  if (HttpError.isHttpError(error)) {
    error.status;     // 422
    error.statusText; // "Unprocessable Entity"
    error.body;       // parsed JSON (or text) payload
    error.headers;    // response headers
  } else if (TimeoutError.isTimeoutError(error)) {
    // request exceeded `timeout`
  }
}

6. Interceptors

const id = api.interceptors.request.use((config) => {
  const headers = new Headers(config.headers);
  headers.set("Authorization", `Bearer ${getToken()}`);
  return { ...config, headers };
});

api.interceptors.response.use(async (response) => {
  if (response.status !== 401) return response;
  await refreshSession();
  return response;
});

api.interceptors.request.eject(id);
api.interceptors.response.clear();

A response interceptor must not read the body (.json(), .text()) and then return the same response — return response.clone() or a new Response instead. Doing otherwise throws a clear error.

7. Timeouts and cancellation

await api.get("/slow", { timeout: 2_000 });          // per request
await api.get("/slow", { signal: controller.signal }); // your own AbortController

Both work together: whichever fires first aborts the request.

8. Escape hatch

api.raw(method, url, config) returns the untouched Response (interceptors still run) when you need streaming or custom parsing.

Response parsing

| Response | Resolves to | | ------------------------------------- | ------------------ | | 204 / 205 / 304, empty body | null | | */*json* | parsed JSON | | text/*, xml, javascript, form | string | | anything else | Blob |

Development

npm run typecheck
npm test        # builds, then runs the suite against a local http server
npm run build   # emits dist/cjs + dist/esm

License

MIT © Andrii Valenko