Go to content
Web development

How to Use Top-Level Fetch in TypeScript

Top-level fetch means calling fetch() in a module’s outermost scope instead of inside a function. It usually uses top-level await, which lets you write await directly at module level. The request starts when the module is imported. This works in browsers and in Node 18 and later, where fetch is a global. TypeScript developers use it to load configuration, startup data, or run small Node scripts.

Whether it actually works depends on three things. Your tsconfig must compile to an ES module format, because CommonJS output cannot pause module evaluation for await. Your environment needs fetch type declarations; the lib setting only supplies types, not runtime behavior. And the data you get back needs runtime validation, because const user = (await response.json()) as User is a promise you make to the compiler, not a guarantee about what the server sent.

What top-level fetch requires in tsconfig

The first requirement is the module format. To use top-level await, set "module": "es2022" or "esnext" for bundled or browser code, or "nodenext" for Node ESM. With "module": "commonjs", the compiler rejects the code: CommonJS modules have no way to suspend evaluation while a promise settles. TypeScript 7 changes the defaults, with strict mode on and an empty types list, so relying on implicit defaults will not carry over.

// config.ts
const response = await fetch("https://api.example.com/config");
export const config = await response.json();

The second requirement is that TypeScript can see the fetch declaration for your environment. In Node 18 and later, fetch exists as a global at runtime, but TypeScript still needs the type. For Node code, install @types/node and set types: ["node"] in tsconfig. For browser code, the DOM lib declares fetch, but the lib setting only supplies type declarations; it does not make document exist in Node. If you add the DOM lib to a Node project to get the fetch types, type-checking passes while the code fails at runtime on browser-only globals.

A browser module also needs to load as a module script (type="module"); classic scripts do not support top-level await. If you see fetch is not defined, the cause is usually the missing declaration or the wrong environment, not the syntax itself.

The cast you make is a promise, not a fact

const response = await fetch("https://api.example.com/users/1");
const user = (await response.json()) as User;
console.log(user.name);

This compiles cleanly. At runtime, user is whatever the server sent, and the cast is invisible to the runtime. If the API renamed name to fullName, user.name is undefined, and the error appears where you read the property, not where you made the request. In a small module that sits one import away from a screen, "cannot read property of undefined" lands far from the actual cause.

The declared type is a promise you make to the compiler, not a fact about the network. The fix is to validate the response where you receive it, so a bad payload fails at the fetch site with a message you control.

Validate the status and the body at the call site

A typed wrapper that checks the HTTP status turns a silent wrong shape into an immediate error:

async function getJson<T>(url: string): Promise<T> {
  const response = await fetch(url);
  if (!response.ok) {
    throw new Error(`HTTP ${response.status} for ${url}`);
  }
  return (await response.json()) as T;
}

This catches status errors but still casts the body. For the body, add a runtime check. The lightweight option is a type guard, a function that checks a value’s shape at runtime and tells TypeScript the type if the check passes:

function isUser(value: unknown): value is User {
  return (
    typeof value === "object" &&
    value !== null &&
    typeof (value as Record<string, unknown>).name === "string"
  );
}

const data: unknown = await response.json();
if (!isUser(data)) throw new Error("Invalid user payload");

For anything beyond a tiny script, Zod, a validation library, replaces hand-written guards with a schema. You define the shape once, and safeParse returns a result with a success flag, so the error path is explicit instead of thrown deep in the parser:

import { z } from "zod";

const UserSchema = z.object({
  id: z.number(),
  name: z.string(),
});

const result = UserSchema.safeParse(await response.json());
if (!result.success) {
  throw new Error(`Invalid user payload: ${result.error.message}`);
}
const user = result.data;

Zod requires a recent TypeScript version and strict mode enabled in tsconfig, so check "strict": true before adopting it. When you build the wrapper, type the options object with a plain interface rather than Partial<Request>; the partial type makes headers possibly undefined, so TypeScript complains when you pass headers to the request. The full Request type is also awkward because it requires many properties you will not set, so define your own options type. For the full wrapper pattern, see Building a Typed Fetch Wrapper in TypeScript.

What changes when the request runs at import time

A module body runs once, on first import, and top-level await pauses the importing module’s evaluation until the promise settles. Three consequences follow.

Importers wait. Any module that imports config.ts does not finish loading until the fetch resolves, so a slow endpoint delays everything downstream in the import graph.

A rejection at module scope is hard to catch. try/catch around an import does not catch it. If the request can fail, handle the failure inside the module: catch it, export a fallback value, or rethrow with context. Do not let the promise reject unhandled.

The request has no timeout by default. A hung server keeps the module suspended. Pass an AbortController signal to fetch to enforce a deadline.

Transient failures deserve a retry. Rate limiting (HTTP 429), network errors, and server errors (5xx) often succeed on a second attempt, and exponential backoff gives the server time to reset the limit by doubling the delay between attempts:

function sleep(ms: number) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function fetchWithRetry(url: string, retries = 3) {
  let delayMs = 500;
  for (let attempt = 0; attempt <= retries; attempt++) {
    try {
      const response = await fetch(url);
      if (response.ok) return response;
      if (response.status !== 429 && response.status < 500) return response;
    } catch {
      // network error; fall through to retry
    }
    if (attempt < retries) {
      await sleep(delayMs);
      delayMs *= 2;
    }
  }
  throw new Error(`Request failed after ${retries} retries`);
}

Do not retry 4xx responses; retrying only wastes the attempt.

When top-level fetch is the wrong tool

Top-level fetch suits a single request in a Node script or a small config-loading module. As the API surface grows, hand-written wrappers and schemas repeat per endpoint, and cast-based typing stays a risk. For full-stack TypeScript, tRPC infers types directly from backend procedures, removing the manual synchronization. For REST APIs with an OpenAPI schema, openapi-fetch generates a type-safe client from the schema; the trade-off is a code-generation build step. Both eliminate the per-endpoint validation you would otherwise write, at the cost of coupling the frontend to the backend’s type system.

For UI code, import-time fetch is usually wrong. The request fires before the component mounts, which makes caching and cancellation awkward, and a slow module blocks the page. Data fetching in a browser belongs in an effect or a library that handles caching and React 19’s fetching behavior. Reserve top-level fetch for server-side bootstrap and scripts, where import-time execution is the point.

More in Web development Back to top ↑