JavaScriptMedium
What is the Fetch API?
The Fetch API is the built-in, promise-based way to make HTTP requests in browsers, Node.js (18+), Deno, Bun and edge runtimes: fetch(url, options) returns a promise of a Response.
Basic flow
const res = await fetch(url, options).- Check
res.ok(status 200-299) orres.status. - Read the body once with
res.json(),res.text(),res.blob(),res.arrayBuffer()orres.formData().
The surprise: HTTP errors do not reject
fetch rejects only on network failures (offline, DNS, CORS blocked, aborted). A 404 or 500 fulfills normally. Always check res.ok and throw yourself.
Common options
method:"POST","PUT","DELETE"...headers: e.g.{ "Content-Type": "application/json", Authorization: "Bearer ..." }body: a string (JSON.stringify(data)),FormData,BloborURLSearchParams. WithFormData, do not setContent-Typeyourself; the browser adds the multipart boundary.signal: anAbortSignalto cancel, e.g.AbortSignal.timeout(5000).credentials:"include"to send cookies cross-origin.cache: control the HTTP cache. In Next.js,fetchalso acceptsnext: { revalidate, tags }.
Good habits
- Wrap fetch in a small helper that checks
ok, parses JSON and throws a meaningful error. - Cancel requests that are no longer needed (component unmount, a new search) with
AbortController. - A body can be read only once; use
res.clone()if you need it twice.
Code example
js
1// A small fetch wrapper with timeout and proper HTTP error handling2async function fetchJson(url, { timeout = 5000, ...options } = {}) {3 const res = await fetch(url, { ...options, signal: AbortSignal.timeout(timeout) });4 if (!res.ok) throw new Error(`HTTP ${res.status} for ${url}`);5 return res.json();6}78// data: URLs let this example run offline; real code would call an API URL9const todo = await fetchJson('data:application/json,{"id":1,"title":"Learn fetch","done":false}');10console.log(todo.title, todo.done); // Learn fetch false1112// POST JSON (shape of a real request)13const request = new Request("https://api.example.com/todos", {14 method: "POST",15 headers: { "Content-Type": "application/json" },16 body: JSON.stringify({ title: "Write tests" }),17});18console.log(request.method, request.headers.get("Content-Type")); // POST application/json1920// Cancel a request that's no longer needed21const controller = new AbortController();22const pending = fetch("data:text/plain,hello", { signal: controller.signal });23controller.abort();24try {25 await pending;26} catch (e) {27 console.log(e.name); // AbortError28}2930// Reading the body: text, json, blob...31const res = await fetch("data:text/plain,plain text body");32console.log(res.ok, res.status, await res.text()); // true 200 plain text body
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.