
How to fetch data from an API in Typescript
Master enterprise data fetching in TypeScript: move beyond native fetch casting to runtime Zod validation, resilient API clients, and OpenAPI codegen.
In enterprise TypeScript applications, the network boundary represents the highest point of systemic risk. Developers routinely write code under the illusion that TypeScript provides end-to-end type safety. However, fetch and Axios generic parameters offer zero runtime guarantees. When an upstream API alters a payload, drops a non-nullable field, or returns a 200 OK with an HTML error page, brittle assertions collapse—often causing silent bugs or unhandled exceptions in critical downstream services.
Building scalable, production-ready TypeScript applications requires treating every HTTP response as untrusted data.
This guide covers the architecture, patterns, and strategies necessary to construct robust, enterprise-grade data-fetching layers in TypeScript.
1. The Fallacy of Type Assertions in Native Fetch
Standard native fetch or popular HTTP clients like Axios allow developers to parameterize network requests with generic types:
// ❌ DANGEROUS: Type assertion masquerading as type safety
interface UserProfile {
id: string;
email: string;
roles: string[];
}
async function getUser(id: string): Promise<UserProfile> {
const response = await fetch(`/api/v1/users/${id}`);
// TypeScript blindly trusts this cast. If the API returns { id: "123" }
// without 'roles', downstream code like user.roles.includes() will throw at runtime.
const data = (await response.json()) as UserProfile;
return data;
}
Generics on HTTP clients act strictly as compile-time assertions (as T). They do not inspect, sanitize, or validate the payload returned over the wire.
The Network Boundary Matrix
| Mechanism | Compile-Time Safety | Runtime Safety | Performance Impact | Setup Complexity |
|---|---|---|---|---|
Type Assertion (as T) |
High (False sense) | None | Zero | Low |
| Manual Type Guards | High | High | Low | Extremely High (Unmaintainable) |
| Schema Parsers (Zod/Valibot) | High | High | Low (Negligible parse time) | Medium |
| Automated OpenAPI Codegen | High | High (with validator) | Low | Medium-High (CI integration) |
To bridge the gap between compile-time types and runtime data, you must enforce validation directly at the network edge.
2. Bridging the Boundary: Runtime Schema Validation with Zod
The canonical solution to network type safety is runtime parsing. By defining schemas via tools like Zod or Valibot, you establish a dynamic barrier that validates untrusted inputs while automatically deriving static TypeScript types.
import { z } from 'zod';
// 1. Define the runtime validation schema
export const UserProfileSchema = z.object({
id: z.string().uuid(),
email: z.string().email(),
roles: z.array(z.string()).default([]),
createdAt: z.string().datetime().transform((val) => new Date(val)),
});
// 2. Infer the compile-time TypeScript type from the schema
export type UserProfile = z.infer<typeof UserProfileSchema>;
// 3. Parse and validate the response
async function getValidatedUser(id: string): Promise<UserProfile> {
const response = await fetch(`/api/v1/users/${id}`);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const rawData: unknown = await response.json();
// .parse() throws ZodError on failure; .safeParse() returns a result object
return UserProfileSchema.parse(rawData);
}
By explicitly typing rawData as unknown, you force the compiler to block direct property access until the data passes schema parsing.
3. Architecting an Enterprise API Client
Production enterprise architectures rarely execute raw fetch calls scattered across features. Instead, network operations are encapsulated inside an abstract, highly configuration-driven API Client.
Architectural Overview
+-----------------------------------------------------------------------+
| Caller Domain |
+-----------------------------------------------------------------------+
|
v
+-----------------------------------------------------------------------+
| Typed HttpClient Core |
| |
| +-------------------+ +--------------------+ +--------------+ |
| | Request Pipeline |-->| Retry & Timeout |-->| Auth/Headers | |
| | Interceptors | | (AbortController) | | Injection | |
| +-------------------+ +--------------------+ +--------------+ |
+-----------------------------------------------------------------------+
|
v
+-----------------------------------------------------------------------+
| Native fetch() |
+-----------------------------------------------------------------------+
|
v
+-----------------------------------------------------------------------+
| Response Middleware & Interceptors |
+-----------------------------------------------------------------------+
|
v
+-----------------------------------------------------------------------+
| Zod Schema Parsing Boundary |
+-----------------------------------------------------------------------+
|
+--------------------+--------------------+
| |
v v
[ Validated Payload ] [ ApiValidationError ]
| |
v v
Domain Logic Execution Structured Telemetry & Logs
Implementing a Modular Network Layer
Here is a enterprise API client implementation featuring interceptors, dynamic error handling, explicit timeouts, and schema validation.
Step 1: Custom Error Taxonomy
export class ApiError extends Error {
constructor(
public readonly status: number,
public readonly statusText: string,
public readonly body: unknown,
message?: string
) {
super(message ?? `HTTP ${status}: ${statusText}`);
this.name = 'ApiError';
}
}
export class ApiValidationError extends Error {
constructor(
public readonly originalError: z.ZodError,
public readonly targetUrl: string
) {
super(`Schema validation failed for request to ${targetUrl}`);
this.name = 'ApiValidationError';
}
}
Step 2: Client Configuration and Core Client Implementation
import { z } from 'zod';
export type RequestInterceptor = (request: Request) => Promise<Request> | Request;
export type ResponseInterceptor = (response: Response) => Promise<Response> | Response;
export interface HttpClientConfig {
baseUrl: string;
defaultHeaders?: Record<string, string>;
timeoutMs?: number;
requestInterceptors?: RequestInterceptor[];
responseInterceptors?: ResponseInterceptor[];
}
export interface FetchOptions<TSchema extends z.ZodTypeAny> extends Omit<RequestInit, 'headers'> {
schema: TSchema;
headers?: Record<string, string>;
timeoutMs?: number;
}
export class HttpClient {
private readonly baseUrl: string;
private readonly defaultHeaders: Record<string, string>;
private readonly timeoutMs: number;
private readonly requestInterceptors: RequestInterceptor[];
private readonly responseInterceptors: ResponseInterceptor[];
constructor(config: HttpClientConfig) {
this.baseUrl = config.baseUrl.replace(/\/$/, '');
this.defaultHeaders = config.defaultHeaders ?? {};
this.timeoutMs = config.timeoutMs ?? 10000;
this.requestInterceptors = config.requestInterceptors ?? [];
this.responseInterceptors = config.responseInterceptors ?? [];
}
async request<TSchema extends z.ZodTypeAny>(
endpoint: string,
options: FetchOptions<TSchema>
): Promise<z.infer<TSchema>> {
const { schema, headers, timeoutMs, ...customConfig } = options;
const url = `${this.baseUrl}/${endpoint.replace(/^\//, '')}`;
// Setup Timeout Abort Controller
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), timeoutMs ?? this.timeoutMs);
// Merge Request Headers
const combinedHeaders = new Headers({
'Content-Type': 'application/json',
...this.defaultHeaders,
...headers,
});
let request = new Request(url, {
...customConfig,
headers: combinedHeaders,
signal: controller.signal,
});
try {
// Execute Request Interceptors
for (const interceptor of this.requestInterceptors) {
request = await interceptor(request);
}
// Perform Fetch
let response = await fetch(request);
// Execute Response Interceptors
for (const interceptor of this.responseInterceptors) {
response = await interceptor(response);
}
if (!response.ok) {
const errorBody = await response.json().catch(() => null);
throw new ApiError(response.status, response.statusText, errorBody);
}
const rawData: unknown = await response.json();
// Parse payload through standard Zod schema boundary
const parseResult = schema.safeParse(rawData);
if (!parseResult.success) {
throw new ApiValidationError(parseResult.error, url);
}
return parseResult.data;
} catch (error: unknown) {
if (error instanceof Error && error.name === 'AbortError') {
throw new Error(`Request to ${url} timed out after ${timeoutMs ?? this.timeoutMs}ms`);
}
throw error;
} finally {
clearTimeout(timeout);
}
}
}
4. Resilience Patterns: Exponential Backoff and Retries
Enterprise clients must gracefully handle transient network errors, blips in dynamic DNS resolutions, and HTTP 429 Rate Limits. Wrapping client executions in explicit retry primitives guarantees higher availability.
Here is an enterprise-grade backoff decorator function:
export interface RetryConfig {
maxRetries: number;
baseDelayMs: number;
maxDelayMs: number;
statusCodesToRetry: number[];
}
const DEFAULT_RETRY_CONFIG: RetryConfig = {
maxRetries: 3,
baseDelayMs: 200,
maxDelayMs: 3000,
statusCodesToRetry: [408, 429, 500, 502, 503, 504],
};
export async function withRetry<T>(
operation: () => Promise<T>,
config: Partial<RetryConfig> = {}
): Promise<T> {
const finalConfig = { ...DEFAULT_RETRY_CONFIG, ...config };
let attempt = 0;
while (true) {
try {
return await operation();
} catch (error: unknown) {
attempt++;
const isRetriableError =
error instanceof ApiError && finalConfig.statusCodesToRetry.includes(error.status);
const isNetworkError = error instanceof TypeError; // Native fetch throws TypeError on network disconnect
if (attempt > finalConfig.maxRetries || (!isRetriableError && !isNetworkError)) {
throw error;
}
// Calculate Jittered Exponential Backoff: delay * 2^attempt + random jitter
const exponentialDelay = finalConfig.baseDelayMs * Math.pow(2, attempt);
const jitter = Math.random() * 100;
const delay = Math.min(exponentialDelay + jitter, finalConfig.maxDelayMs);
console.warn(
`[Network Warning] Retrying request (Attempt ${attempt}/${finalConfig.maxRetries}) after ${delay.toFixed(0)}ms due to: ${error instanceof Error ? error.message : String(error)}`
);
await new Promise((resolve) => setTimeout(resolve, delay));
}
}
}
Applying Resilience to API Operations
const apiClient = new HttpClient({
baseUrl: 'https://api.enterprise.domain/v1',
defaultHeaders: { 'X-Correlation-ID': crypto.randomUUID() }
});
export async function fetchOrderDetails(orderId: string) {
return withRetry(() =>
apiClient.request(`orders/${orderId}`, {
method: 'GET',
schema: OrderSchema,
})
);
}
5. End-to-End Type Safety via OpenAPI Code Generation
Manually constructing Zod schemas for hundreds of enterprise endpoints creates duplication and code drift between backend specs and frontend types. Modern architecture uses Contract-Driven Development.
By leveraging tools like openapi-typescript, you can compile an OpenAPI/Swagger spec into static TypeScript interfaces directly inside your build pipelines.
Modern Codegen Pipeline Setup
npm install -D openapi-typescript typescript
Add a execution task in package.json:
{
"scripts": {
"generate:api": "openapi-typescript https://api.enterprise.domain/swagger/v1/swagger.json --output ./src/types/api-schema.ts"
}
}
Leveraging Derived OpenAPI Types in Enterprise Code
Generated types can be combined with native standard fetch wrappers using utility libraries like openapi-fetch:
import createClient from "openapi-fetch";
import type { paths } from "./types/api-schema"; // Automatically generated file
// Instantiate a fully typed native client tied directly to backend OpenAPI Spec
const client = createClient<paths>({ baseUrl: "https://api.enterprise.domain/v1" });
async function getInventoryItem(itemId: string) {
const { data, error } = await client.GET("/inventory/{id}", {
params: {
path: { id: itemId },
},
});
if (error) {
// Painlessly handle typed API errors matching backend specs
console.error(error.message, error.errorCode);
return null;
}
// `data` is 100% typed compile-time based on the backend OpenAPI schema definition
return data;
}
6. Server-Side Data Fetching in Node.js / Next.js Environments
Data fetching patterns differ when operating inside modern server-side environments (Node.js 18+, Next.js App Router, Remix) versus frontend browsers.
Server-Side Requirements Checklist
- Connection Pooling and Keep-Alive: Ensure high performance using modern engines like
undici(the underlying engine of Node’s nativefetch). - Context-Aware Tracing: Inject distributed tracing headers (
traceparent, W3C Trace Context) to trace requests across microservice boundaries. - Caching & Revalidation: Leverage server-side HTTP caching mechanisms explicitly.
import { AsyncLocalStorage } from 'node:async_hooks';
// AsyncLocalStorage tracks request contexts (like Correlation/Trace IDs) across async calls
export const tracingContext = new AsyncLocalStorage<{ traceId: string }>();
export async function serverSideFetch<T>(
url: string,
schema: z.ZodType<T>
): Promise<T> {
const context = tracingContext.getStore();
const headers: Record<string, string> = {
'Accept': 'application/json',
...(context?.traceId ? { 'traceparent': context.traceId } : {}),
};
const response = await fetch(url, {
headers,
// Server-side explicit cache policy setup (e.g., Next.js extended fetch options)
next: { revalidate: 60 }
} as RequestInit);
if (!response.ok) {
throw new ApiError(response.status, response.statusText, null);
}
const data: unknown = await response.json();
return schema.parse(data);
}
7. Operational Checklist for Production Deployment
Before pushing TypeScript API integration pipelines to production, evaluate your architecture against this checklist:
[ ] Zero Trust Boundary Parsing
- Are ALL external network payloads validated with a runtime parser (Zod/Valibot)?
- Is the raw response explicitly typed as `unknown` before schema parsing?
[ ] Structured Error Handling
- Do custom errors distinguish between Network/Timeout failures, HTTP status errors,
and Schema Validation failures?
- Are validation errors sanitized so sensitive PII is not leaked into client logs?
[ ] Timeout Management
- Does every network request declare an explicit upper timeout boundary via `AbortController`?
[ ] Resiliency Primitives
- Are transient status codes (429, 502, 503, 504) configured with jittered
exponential backoff?
- Are non-idempotent calls (POST/PATCH) explicitly protected from unsafe retries?
[ ] Observability & Telemetry
- Are distributed tracing IDs (`X-Correlation-ID` or `traceparent`) propagated automatically
via request interceptors?
- Are API call durations monitored using performance markers?
Conclusion
Building enterprise-grade data fetching layers in TypeScript requires shifting from simple compile-time assertions to robust, boundary-level runtime validation. Treating HTTP responses as untrusted data (unknown) and routing them through Zod schemas or automated OpenAPI tooling builds a resilient architecture capable of failing gracefully, protecting domain logic, and insulating applications against unexpected API changes.