Multiple ways to fetch data from an API in Typescript, there usage and when to use them?

Multiple ways to fetch data from an API in Typescript, there usage and when to use them?

A deep dive into TypeScript data fetching strategies: Native Fetch + Zod, Axios pipelines, TanStack Query, tRPC, and OpenAPI. Learn when to use each.

In enterprise TypeScript applications, network communication is often the primary source of runtime failures, subtle state bugs, and type-safety degradation. While TypeScript provides compile-time guarantees within your application’s boundaries, the network boundary is inherently non-deterministic.

A common antipattern in TypeScript codebases is trusting API contracts blindly:

// ❌ Dangerous: Casts unvalidated JSON directly to a TypeScript interface
const response = await fetch('/api/v1/users/42');
const user: User = await response.json(); 

The code above presents a false sense of security. TypeScript’s type system is erased at compile time; if the backend returns null, renames a field, or returns an HTTP 500 HTML error page, your application will crash at runtime with TypeError: Cannot read properties of undefined.

This guide explores the primary strategies for data fetching in modern enterprise TypeScript applications, analyzing their architectural trade-offs, type boundary safety, and ideal use cases.


Architectural Overview: The Data Fetching Spectrum

Choosing a data fetching strategy requires balancing abstraction level, bundle size overhead, state management capabilities, and end-to-end type safety guarantees.

Low Abstraction / High Control                       High Abstraction / End-to-End Safety
<---------------------------------------------------------------------------------------->
[ Native fetch + Zod ] ---> [ Axios Pipeline ] ---> [ TanStack Query ] ---> [ tRPC / OpenAPI ]
  - 0 Dependencies           - Request Pipeline       - Cache / Retries        - Zero Boilerplate
  - Explicit Runtime Checks  - Interceptors           - Server State Mgmt      - E2E Schema Coupling

Strategy 1: Native fetch with Runtime Schema Validation (Zod)

The modern standard for zero-dependency API interactions combines the native browser/Node.js fetch API with runtime schema validation libraries like Zod or Valibot.

Architectural Blueprint

Instead of asserting types via generic parameter casting (which native fetch doesn’t even support natively without custom wrappers), we parse the incoming JSON payload against a runtime Zod schema.

┌──────────────┐     HTTP Request     ┌──────────────┐
│  TypeScript  │ ───────────────────> │  REST API    │
│  Application │                      └──────┬───────┘
└──────┬───────┘                             │
       │                                     │ JSON Response
       │      ┌──────────────────────┐       │
       └─────>│ Zod Schema Validation│ <─────┘
              └──────────┬───────────┘
                         │
        ┌────────────────┴────────────────┐
        ▼                                 ▼
[ Valid Data: Type T ]        [ Invalid: SchemaError ]

Production Implementation

Below is a robust, production-grade wrapper that provides type safety, automatic response validation, and structured error handling using a functional Result pattern.

import { z } from 'zod';

// Standardized Result type to avoid try/catch control flow bloat
export type Result<T, E = Error> =
  | { success: true; data: T }
  | { success: false; error: E };

export class HttpError extends Error {
  constructor(
    public readonly status: number,
    public readonly statusText: string,
    public readonly body: unknown
  ) {
    super(`HTTP ${status}: ${statusText}`);
    this.name = 'HttpError';
  }
}

export class ValidationError extends Error {
  constructor(public readonly zodError: z.ZodError) {
    super('Response validation failed');
    this.name = 'ValidationError';
  }
}

interface FetchOptions extends RequestInit {
  timeoutMs?: number;
}

export async function safeFetch<T>(
  url: string,
  schema: z.ZodType<T>,
  options: FetchOptions = {}
): Promise<Result<T, HttpError | ValidationError | Error>> {
  const { timeoutMs = 8000, ...init } = options;

  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), timeoutMs);

  try {
    const response = await fetch(url, {
      ...init,
      signal: controller.signal,
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        ...init.headers,
      },
    });

    if (!response.ok) {
      let errorBody: unknown;
      try {
        errorBody = await response.json();
      } catch {
        errorBody = await response.text();
      }
      return {
        success: false,
        error: new HttpError(response.status, response.statusText, errorBody),
      };
    }

    const rawData = await response.json();
    
    // Validate payload at runtime
    const parseResult = schema.safeParse(rawData);
    if (!parseResult.success) {
      return {
        success: false,
        error: new ValidationError(parseResult.error),
      };
    }

    return { success: true, data: parseResult.data };
  } catch (err: unknown) {
    if (err instanceof Error && err.name === 'AbortError') {
      return { success: false, error: new Error(`Request timed out after ${timeoutMs}ms`) };
    }
    return {
      success: false,
      error: err instanceof Error ? err : new Error(String(err)),
    };
  } finally {
    clearTimeout(timeoutId);
  }
}

Usage Example

const UserSchema = z.object({
  id: z.string().uuid(),
  email: z.string().email(),
  role: z.enum(['ADMIN', 'USER', 'GUEST']),
  createdAt: z.string().datetime().transform((val) => new Date(val)),
});

type User = z.infer<typeof UserSchema>;

async function getUserProfile(userId: string) {
  const result = await safeFetch(
    `/api/v1/users/${userId}`,
    UserSchema,
    { timeoutMs: 5000 }
  );

  if (!result.success) {
    if (result.error instanceof ValidationError) {
      console.error('API response violated contract:', result.error.zodError.format());
    } else if (result.error instanceof HttpError) {
      console.error(`API Error ${result.error.status}:`, result.error.body);
    }
    return null;
  }

  // result.data is strictly typed as User
  console.log(`User email: ${result.data.email}, joined: ${result.data.createdAt.getFullYear()}`);
  return result.data;
}

When to Use

  • Microservices & SDKs: Building low-overhead SDKs where adding heavy HTTP client dependencies is undesirable.
  • Edge Runtimes: Cloudflare Workers, Vercel Edge Functions, or Deno where bundle size and native web APIs are critical.
  • Strict Data Contracts: When consuming third-party APIs that may drift from documented specifications.

Strategy 2: Enterprise Axios with Interceptor Pipelines

While native fetch has improved significantly, Axios remains heavily used in enterprise systems due to built-in request/response interceptors, automatic JSON transformation, cross-platform consistency (Node.js http module vs Browser XMLHttpRequest/fetch), and upload/download progress tracking.

Enterprise Token Refresh & Interceptor Mutex

A classical problem in enterprise SPA architecture is silent token refresh: when an API call returns a 401 Unauthorized, the client must pause outgoing requests, acquire a new JWT using a refresh token, retry the failed request, and resume pending requests.

import axios, { AxiosInstance, AxiosError, InternalAxiosRequestConfig } from 'axios';

interface FailedRequestQueueItem {
  resolve: (token: string) => void;
  reject: (error: unknown) => void;
}

export class ApiClient {
  private axiosInstance: AxiosInstance;
  private isRefreshing = false;
  private failedQueue: FailedRequestQueueItem[] = [];

  constructor(baseURL: string) {
    this.axiosInstance = axios.create({
      baseURL,
      timeout: 10000,
      headers: { 'Content-Type': 'application/json' },
    });

    this.setupInterceptors();
  }

  private processQueue(error: unknown, token: string | null = null): void {
    this.failedQueue.forEach((prom) => {
      if (error) {
        prom.reject(error);
      } else if (token) {
        prom.resolve(token);
      }
    });
    this.failedQueue = [];
  }

  private setupInterceptors(): void {
    // Request Interceptor: Attach Auth Header
    this.axiosInstance.interceptors.request.use(
      (config: InternalAxiosRequestConfig) => {
        const token = localStorage.getItem('access_token');
        if (token && config.headers) {
          config.headers.Authorization = `Bearer ${token}`;
        }
        return config;
      },
      (error) => Promise.reject(error)
    );

    // Response Interceptor: Silent Token Refresh Mutex
    this.axiosInstance.interceptors.response.use(
      (response) => response,
      async (error: AxiosError) => {
        const originalRequest = error.config as InternalAxiosRequestConfig & { _retry?: boolean };

        if (error.response?.status === 401 && !originalRequest._retry) {
          if (this.isRefreshing) {
            return new Promise((resolve, reject) => {
              this.failedQueue.push({ resolve, reject });
            })
              .then((token) => {
                if (originalRequest.headers) {
                  originalRequest.headers.Authorization = `Bearer ${token}`;
                }
                return this.axiosInstance(originalRequest);
              })
              .catch((err) => Promise.reject(err));
          }

          originalRequest._retry = true;
          this.isRefreshing = true;

          try {
            const newToken = await this.refreshToken();
            localStorage.setItem('access_token', newToken);
            
            if (originalRequest.headers) {
              originalRequest.headers.Authorization = `Bearer ${newToken}`;
            }
            
            this.processQueue(null, newToken);
            return this.axiosInstance(originalRequest);
          } catch (refreshError) {
            this.processQueue(refreshError, null);
            this.onAuthFailure();
            return Promise.reject(refreshError);
          } finally {
            this.isRefreshing = false;
          }
        }

        return Promise.reject(error);
      }
    );
  }

  private async refreshToken(): Promise<string> {
    const refreshToken = localStorage.getItem('refresh_token');
    const response = await axios.post<{ accessToken: string }>('/api/v1/auth/refresh', { refreshToken });
    return response.data.accessToken;
  }

  private onAuthFailure(): void {
    localStorage.clear();
    window.location.href = '/login';
  }

  public get instance(): AxiosInstance {
    return this.axiosInstance;
  }
}

When to Use

  • Complex Authentication Pipelines: Multi-tenant apps requiring session recovery, token rotation queues, or transparent request mutation.
  • Node.js Legacy Compatibility: Applications running across hybrid Node.js/Browser environments requiring robust proxying and timeout mechanisms.
  • Progress Monitoring: Applications needing built-in upload/download progress metrics (e.g., enterprise document management).

Strategy 3: Server-State Management via TanStack Query (React Query)

In client-side applications (React, Vue, Angular, Solid), raw data fetching creates massive state boilerplate: isLoading, isError, state synchronization across components, cache invalidation, and deduplication.

TanStack Query decouples data-fetching mechanics from component state, acting as an asynchronous state manager.

Component Tree              TanStack Query Engine            Network / API
┌───────────────┐           ┌──────────────────┐           ┌──────────────┐
│  Component A  │ ────────> │                  │           │              │
└───────────────┘           │  Query Cache     │ ────────> │  REST / REST │
┌───────────────┐           │  Deduplication   │           │  Endpoints   │
│  Component B  │ ────────> │  Garbage Collect │ <──────── │              │
└───────────────┘           └──────────────────┘           └──────────────┘

Strictly Typed Query Key Factories & Hooks

To avoid magic strings and key collisions in large codebases, implement the Query Key Factory Pattern alongside Zod validation.

import { useQuery, useMutation, useQueryClient, UseQueryResult } from '@tanstack/react-query';
import { z } from 'zod';
import { safeFetch } from './safeFetch'; // From Strategy 1

// 1. Define Schemas & Types
const OrderSchema = z.object({
  id: z.string(),
  totalAmount: z.number(),
  status: z.enum(['PENDING', 'SHIPPED', 'DELIVERED']),
});

type Order = z.infer<typeof OrderSchema>;

// 2. Query Key Factory Pattern
export const orderKeys = {
  all: ['orders'] as const,
  lists: () => [...orderKeys.all, 'list'] as const,
  list: (filters: string) => [...orderKeys.lists(), { filters }] as const,
  details: () => [...orderKeys.all, 'detail'] as const,
  detail: (id: string) => [...orderKeys.details(), id] as const,
};

// 3. Strongly Typed Fetcher Hook
export function useOrderDetails(orderId: string): UseQueryResult<Order, Error> {
  return useQuery({
    queryKey: orderKeys.detail(orderId),
    queryFn: async ({ signal }) => {
      const result = await safeFetch(`/api/v1/orders/${orderId}`, OrderSchema, { signal });
      if (!result.success) {
        throw result.error;
      }
      return result.data;
    },
    staleTime: 1000 * 60 * 5, // Data is fresh for 5 minutes
    gcTime: 1000 * 60 * 30,    // Cache preserved for 30 minutes
    retry: (failureCount, error) => {
      // Don't retry on client errors (404, 401, validation errors)
      if (error.message.includes('HTTP 4') || error.name === 'ValidationError') return false;
      return failureCount < 3;
    },
  });
}

When to Use

  • Interactive Single-Page Applications (SPAs): Where multiple components depend on identical async server data.
  • Optimistic UI Updates: Apps requiring real-time visual feedback before backend confirmation (e.g., toggling items, task management).
  • Polling & Background Refetching: Applications that require dashboards to stay synchronized with backend events without WebSockets.

Strategy 4: End-to-End Type Safety (tRPC & OpenAPI Fetch)

The ultimate solution to boundary safety is eliminating boundary translation manually. Instead of maintaining duplicate TypeScript interfaces on the client and server, RPC and Contract-First tooling generate shared types directly from backend schemas.

1. tRPC (Monorepo / Full-Stack TypeScript)

If both your frontend and backend are written in TypeScript (e.g., Next.js, Express, Fastify inside a monorepo), tRPC provides absolute, zero-codegen end-to-end type safety.

// SERVER: router.ts (Backend)
import { initTRPC } from '@trpc/server';
import { z } from 'zod';

const t = initTRPC.create();

export const appRouter = t.router({
  getUserById: t.procedure
    .input(z.object({ id: z.string().uuid() }))
    .query(async ({ input }) => {
      // input is inferenced as { id: string }
      return { id: input.id, name: 'Ada Lovelace', role: 'ENGINEER' };
    }),
});

// Export ONLY the type definition of the router
export type AppRouter = typeof appRouter;
// CLIENT: client.ts (Frontend)
import { createTRPCClient, httpBatchLink } from '@trpc/client';
import type { AppRouter } from '../server/router';

// Pass AppRouter generic to client creation
const trpc = createTRPCClient<AppRouter>({
  links: [
    httpBatchLink({ url: 'http://localhost:3000/trpc' }),
  ],
});

async function run() {
  // 100% Type-safe! Intellisense works for inputs AND outputs.
  // Typos in route name or input params trigger compile errors!
  const user = await trpc.getUserById.query({ id: '123e4567-e89b-12d3-a456-426614174000' });
  console.log(user.name); 
}

2. OpenAPI Fetch (openapi-fetch) (Polyglot Backends)

If your backend is written in Go, Java, Rust, or Python, but exposes an OpenAPI/Swagger spec, tools like openapi-fetch generate lightweight TypeScript types directly from the OpenAPI schema file.

# Generate types from OpenAPI spec
npx openapi-typescript https://api.example.com/v3/openapi.json -o ./src/schema.d.ts
// CLIENT: openapi-client.ts
import createClient from 'openapi-fetch';
import type { paths } from './schema'; // Generated from backend spec

const client = createClient<paths>({ baseUrl: 'https://api.example.com/v3' });

async function fetchInvoice() {
  // Path, params, and response types are fully inferred from the OpenAPI spec!
  const { data, error } = await client.GET('/invoices/{id}', {
    params: {
      path: { id: 'inv_1092' },
      query: { format: 'summary' },
    },
  });

  if (error) {
    // Typed error schema matching HTTP response specs
    console.error(error.message);
    return;
  }

  console.log(data.totalAmount);
}

When to Use

  • tRPC: Full-stack TypeScript monorepos (Next.js, Turborepo, Nx) where team ownership spans both client and server code.
  • OpenAPI Fetch: Microservice enterprise setups with polyglot backends (Go/Java/Python) where API contracts are maintained via OpenAPI specifications.

Strategy 5: GraphQL with Typed Document Nodes

When consuming GraphQL APIs, relying on generic string query strings bypasses TypeScript’s static checks. GraphQL Code Generator with TypedDocumentNode provides strict static analysis over GraphQL operations.

# userQuery.graphql
query GetUserProfile($id: ID!) {
  user(id: $id) {
    id
    name
    email
  }
}
// Generated by @graphql-codegen/typed-document-node
import { TypedDocumentNode } from '@graphql-typed-document-node/core';
import { executeGraphQL } from './gqlClient';

// Compiled type metadata attached to the query node itself
import { GetUserProfileDocument, GetUserProfileQuery, GetUserProfileQueryVariables } from './generated/graphql';

async function fetchUser(userId: string) {
  // Input arguments and return type are linked directly to GetUserProfileDocument
  const data = await executeGraphQL(GetUserProfileDocument, { id: userId });
  
  // data is automatically typed as GetUserProfileQuery
  console.log(data.user?.email);
}

When to Use

  • Applications querying large graph datasets with flexible component data requirements.
  • Enterprise organizations with unified GraphQL Gateway / Federation layers.

Comparative Enterprise Decision Matrix

Dimension Native fetch + Zod Axios + Interceptors TanStack Query tRPC / OpenAPI Fetch
Bundle Impact Near-zero (~1KB Zod optional) ~13KB minified ~13KB minified < 1KB (runtime wrapper)
Runtime Validation Explicit & Strict Manual setup Custom Fetcher Inherent via Schema
State & Cache None (Manual) None (Manual) Best-in-Class Via Plugins
Backend Agnostic Yes Yes Yes tRPC (TS-only) / OpenAPI (Polyglot)
Retry / Backoff Manual implementation Via Plugins Built-in Configurable
Type Boundary Safety High (Runtime checked) Low (Blind casting) Depends on Fetcher Absolute (Compile/Runtime)
Learning Curve Low Low Medium Low to Medium

Production Resilience & Engineering Best Practices

Regardless of your chosen transport or abstraction layer, enterprise data fetching layers must adhere to standard resilience patterns:

1. Functional Error Handling over Throwing Exceptions

Throwing exceptions for expected domain failures (e.g., 404 Not Found, 422 Unprocessable Entity) creates chaotic control flows across UI components. Use discriminated unions or Result containers to handle error branches explicitly.

type ApiResponse<T> =
  | { success: true; data: T }
  | { success: false; error: { code: 'NOT_FOUND' | 'UNAUTHORIZED' | 'VALIDATION'; message: string } };

2. Defensive Timeout Policies with AbortSignal

Never send network requests without explicit timeouts. Unbounded requests consume connection pools and cause UI components to hang indefinitely.

function fetchWithTimeout(resource: string, options: RequestInit & { timeout?: number } = {}) {
  const { timeout = 8000, ...fetchOptions } = options;
  const controller = new AbortController();
  const id = setTimeout(() => controller.abort(), timeout);

  return fetch(resource, {
    ...fetchOptions,
    signal: controller.signal,
  }).finally(() => clearTimeout(id));
}

3. Circuit Breaker & Exponential Backoff

For high-volume microservices or mission-critical UIs, implement exponential backoff with random jitter to prevent “thundering herd” scenarios when services recover from outages.

async function backoffRetry<T>(
  fn: () => Promise<T>,
  retries = 3,
  delay = 1000
): Promise<T> {
  try {
    return await fn();
  } catch (error) {
    if (retries <= 0) throw error;
    
    // Exponential backoff with full jitter
    const jitteredDelay = Math.random() * delay;
    await new Promise((res) => setTimeout(res, jitteredDelay));
    
    return backoffRetry(fn, retries - 1, delay * 2);
  }
}

Architectural Verdict & Guidance

Selecting the ideal data fetching strategy depends directly on application domain and infrastructure setup:

  1. Building a React/Vue SPA connecting to REST APIs? Use TanStack Query paired with Native fetch + Zod schemas. This handles state caching while validating incoming payloads at the boundary.

  2. Working in a Full-Stack TypeScript Monorepo? Adopt tRPC. It eliminates manual mapping, provides real-time compiler feedback across boundary changes, and speeds up iteration.

  3. Integrating with Polyglot Microservices? Enforce OpenAPI contract schemas and consume them via openapi-fetch combined with runtime Zod guards.

  4. Maintaining Legacy Codebases or Complex Token Interceptors? Implement Axios with structured Interceptor Pipelines, wrapping responses in functional Result containers to keep error boundaries deterministic.