contentintech
Cheatsheets/Fetch API
Frontend

Fetch API

Request JSON, handle HTTP failures and cancel stale requests.

Read responses

const response = await fetch('/api/items');Send a same-origin GET request
if (!response.ok) throw new Error(`HTTP ${response.status}`);Check HTTP status; 4xx/5xx do not automatically reject fetch
const data = await response.json();Parse a JSON body once
const text = await response.text();Parse text instead of JSON

Request options

fetch('/api/items', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'Ada' }) });Send JSON
fetch('/api/items', { credentials: 'include' });Include credentials; cross-origin requests still need valid CORS policy
fetch('/api/items', { cache: 'no-store' });Avoid the browser HTTP cache for this request
fetch('/api/items', { headers: { Accept: 'application/json' } });Request a JSON representation

Cancellation

const controller = new AbortController();Create a cancellation controller
fetch('/api/items', { signal: controller.signal });Connect a request to its signal
controller.abort();Cancel an in-flight request
fetch('/api/items', { signal: AbortSignal.timeout(5000) });Abort after five seconds in supporting runtimes

Section navigation