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.

Typescript Node Data Fetching

Code

snippet
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');
}