5. Full-Stack Integration & Performance

Consuming Authenticated APIs: Typed Fetch Clients, Storage & Optimistic UI

Connect TypeScript frontends safely to REST backends: build a generic request<T>() wrapper, handle 401 token expiry, compare localStorage vs HttpOnly cookies (XSS vs CSRF), and roll back optimistic updates.

4 min readUpdated 2026-12-01
In This Lesson
  • Wrap fetch() inside a reusable typed apiClient<T>() handling headers, JSON, and HTTP errors
  • Compare localStorage vs HttpOnly cookies for auth tokens (XSS vs CSRF tradeoffs)
  • Implement optimistic UI updates with automatic rollback on server error

Now let's bridge your frontend directly to backend APIs (like the FastAPI service from Python Backend, APIs & Databases)! Instead of scattering fetch() calls with duplicated Authorization headers and res.ok checks across 20 components, build one central typed API client.

1. Centralizing Requests with apiRequest<T>()

Typed Frontend API Client ↔ Backend Endpoint Flow

1. HTTP Request

Method + URL + JSON

2. Auth & CORS

401 / 403 guard

3. Pydantic Schema

422 on bad fields

4. Route + Repo

Depends(get_db) + SQL ?

5. Public JSON

200 / 201 / 204

Every request passes through security/validation gates before touching SQLite, and returns only safe response_model fields.

ts
export class ApiHttpError extends Error {
  constructor(public status: number, message: string) {
    super(message);
  }
}

export async function apiRequest<T>(
  path: string,
  options: RequestInit & { token?: string } = {}
): Promise<T> {
  const { token, headers, ...rest } = options;
  const res = await fetch("https://api.example.com" + path, {
    ...rest,
    headers: {
      "Content-Type": "application/json",
      ...(token ? { Authorization: "Bearer " + token } : {}),
      ...headers,
    },
  });

  if (res.status === 401) {
    // Trigger logout / token refresh centrally!
  }
  if (!res.ok) {
    throw new ApiHttpError(res.status, "Request failed: " + res.status);
  }
  if (res.status === 204) return undefined as T;
  return (await res.json()) as T;
}

2. Where Should Auth Tokens Live? (localStorage vs HttpOnly Cookies)

Storage MechanismAccessible from JavaScript?Vulnerable to XSS?Vulnerable to CSRF?
localStorage / sessionStorageYes (localStorage.getItem)Yes (any injected script can steal it)No (only sent explicitly via Authorization header)
HttpOnly; Secure; SameSite=Lax CookieNo (hidden from JS!)Protected from token theftMitigated cleanly via SameSite=Lax / CSRF tokens
  • For production login sessions, HttpOnly; Secure; SameSite=Lax cookies set by your backend protect tokens from JavaScript theft.
  • Regardless of storage, always prevent XSS (textContent, sanitized HTML) so attackers can never run scripts on your origin!

3. Optimistic UI Updates (With Safe Rollback)

When a user clicks Like or Mark Complete, waiting 400ms for the server makes your app feel sluggish. Optimistic UI updates the screen immediately, sends the PATCH request in the background, and rolls back to the previousState snapshot if the server rejects!

Try It Yourself in the Playground

Test an Optimistic Toggle with Automatic Server-Error Rollback live in the browser below (toggle "Simulate Server Error" on and off to see both paths!):

HTML / CSS / JSTry It Live: Optimistic UI Toggle with Rollback
Live Browser Preview

Mini-Challenge: Why is if (res.status === 204) return undefined; important inside apiRequest<T>() for DELETE endpoints?

Quick Checkpoints

Check Your Understanding

Why are HttpOnly cookies safer than localStorage for storing long-lived session tokens?

Check Your Understanding

In an Optimistic UI update, what MUST happen inside the catch block if the background PATCH request fails?