Call APIs from the browser: fetch, auth, and error handling.
Call APIs from the browser: fetch, auth, and error handling.
Use fetch(url, { method, headers, body }) for GET, POST, PUT, PATCH, DELETE. The response is a Promise; check response.ok (or status code), then response.json(), .text(), or .blob() depending on the API.
Always handle three states in the UI: loading (show spinner or skeleton), success (show data), and error (show message and retry if appropriate). Do not assume the network or server will always succeed.
For authenticated APIs, send Authorization: Bearer <token> in the request header or rely on cookies (prefer httpOnly for tokens). If the API is on a different origin, the server must send CORS headers (e.g. Access-Control-Allow-Origin) or the browser blocks the response.
Handle 401 (unauthorized) by redirecting to login or refreshing the token. Store tokens securely; avoid localStorage for tokens if you can use httpOnly cookies to reduce XSS risk.
Centralize the API base URL and auth logic (e.g. a small client module or axios/fetch wrapper). Use a consistent error shape from the API (e.g. { code, message }) so the UI can show user-friendly messages.
Consider retries for transient failures, timeouts, and request cancellation (AbortController) for navigations. [MDN – Client-side APIs](https://developer.mozilla.org/en-US/docs/Learn_web_development/Getting_started).
Key takeaways
Related concepts
Explore topics that connect to this one.
Ready to see how this works in the cloud?
Switch to Career Paths for structured paths (e.g. Developer, DevOps) and provider-specific lessons.
View role-based pathsSign in to track your progress and mark lessons complete.
Questions? Discuss in the community or start a thread below.
Join DiscordSign in to start or join a thread.