Node.js Typed Data Fetching

Fetch remote data in Node.js with TypeScript using generic HTTP wrappers, retry logic with exponential backoff, response parsing with Zod, and.

TypescriptNodeData Fetching

Code

typescriptsnippet
19 lines
import { z } from 'zod';

async function fetchWithRetry<T>(
  url: string,
  schema: z.ZodSchema<T>,
  retries = 3,
): Promise<T> {
  for (let i = 0; i < retries; i++) {
    try {
      const res = await fetch(url, { signal: AbortSignal.timeout(5000) });
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      return schema.parse(await res.json());
    } catch (err) {
      if (i === retries - 1) throw err;
      await new Promise((r) => setTimeout(r, 2 ** i * 1000));
    }
  }
  throw new Error('Unreachable');
}

What the code does

Count the function fetchWithRetry as the entire surface area of Node.js Typed Data Fetching.

The file repeats itself only inside for (let i = 0; i < retries; i++). Await points sequence the asynchronous work; a rejection lands at the awaiting line. The import line is the dependency contract: z comes from zod and nothing else. The Error throw is the give-up path: it fires only after the loop above it has gone through every attempt without the early return firing.

What to watch for

  • External dependency: zod — install it before running the snippet.
  • Uses fetch, so it needs a browser context — it will not run as-is in Node without shims.
  • The guard !res.ok short-circuits the flow with an early throw when its condition holds.

Statements that matter

await new Promise((r) => setTimeout(r, 2 ** i * 1000));
return schema.parse(await res.json());
const res = await fetch(url, { signal: AbortSignal.timeout(5000) });

Interactive Tools for This Topic

FAQ

What makes the code give up?
Only when the loop gives up — `Error` fires once the final attempt has been tried and no early return happened.
Which packages must be installed first?
Yes. The imports resolve to `zod`, which the package manager must provide.