On this page
  1. Fetch & Networking
  2. Contents
  3. fetch() with Status Check & Timeout
  4. Building Safe URLs (URL & URLSearchParams)

Fetch & Networking

Prev: apis | Up: apis | Next: Storage & State
Rel: Promise & Async, Forms, Validation & Fetch
Ref: MDN Web Docs — Fetch API
Tags: #public #web #platform #apis #networking


Contents


fetch() with Status Check & Timeout

fetch() only rejects on network failures or aborts — not on HTTP 404 or 500 responses. Always check res.ok, and attach AbortSignal.timeout(ms) to bound latency:

async function fetchJson(url, { timeoutMs = 5000 } = {}) {
  const res = await fetch(url, {
    headers: { Accept: "application/json" },
    signal: AbortSignal.timeout(timeoutMs),
  });
  if (!res.ok) {
    throw new Error(`HTTP ${res.status} ${res.statusText}`);
  }
  return res.json();
}

Building Safe URLs (URL & URLSearchParams)

const url = new URL("https://api.example.com/search");
url.searchParams.set("q", "web platform");
url.searchParams.set("page", "1");
console.log(url.href);

Linked from

Related notes