Lesson 29 of 50Async JavaScript
Working with APIs
Talk to REST APIs from the browser like a professional: methods, status codes, query strings, auth, CORS, UI states, pagination, caching and a typed client.
Almost every app you build will spend its life talking to someone else's server: a weather service, a payment provider, your own backend. The previous lesson showed how fetch works. This one is about the conversation itself: what the server expects you to send, what its answers mean, and how to turn those answers into a page that behaves well when the network is slow, the list is empty or the server is down. You will finish with a small typed API client you can reuse in any project.
REST from the client's side
An API (application programming interface) is a set of URLs a program can call. A REST API organises those URLs around resources, the nouns of the app: /users, /users/42, /users/42/orders. You say what you want to do with a resource using an HTTP method, the verb:
| Method | Meaning | Example | Safe to repeat? |
|---|---|---|---|
GET | Read | GET /recipes?tag=vegan | Yes |
POST | Create (or trigger an action) | POST /recipes with a JSON body | No |
PUT | Replace a whole resource | PUT /recipes/7 | Yes |
PATCH | Change some fields | PATCH /recipes/7 with { "title": "..." } | Usually |
DELETE | Remove | DELETE /recipes/7 | Yes |
"Safe to repeat" is the technical idea of idempotency: sending the request twice leaves the server in the same state as sending it once. It matters because it tells you what you may retry automatically. Retrying a GET is harmless; retrying a POST /payments might charge someone twice.
The server answers with a status code, a three-digit number grouped by its first digit: 2xx success, 3xx redirect, 4xx you made a mistake, 5xx the server made a mistake.
| Code | Name | What your UI should do |
|---|---|---|
| 200 | OK | Show the data |
| 201 | Created | Show the new item (often returned in the body) |
| 204 | No Content | Success with no body: do not call res.json() |
| 400 / 422 | Bad Request / Unprocessable | Show validation messages next to the fields |
| 401 | Unauthorized | Not logged in (or the token expired): send to sign-in |
| 403 | Forbidden | Logged in but not allowed: explain, do not retry |
| 404 | Not Found | Show a "not found" state |
| 409 | Conflict | Someone else changed it: reload and try again |
| 429 | Too Many Requests | Slow down; respect the Retry-After header |
| 500 / 503 | Server Error / Unavailable | Show an error with a retry button |
Match each response to what the client should do.
Headers and JSON
Headers are key-value lines that travel with every request and response, describing the message rather than carrying it. The three you will set most:
Content-Type: application/jsontells the server your body is JSON.Accept: application/jsonasks for JSON back.Authorization: Bearer <token>proves who you are (more below).
Bodies are almost always JSON: send with JSON.stringify(data), read with await res.json().
Query strings with URLSearchParams
Filters, search terms and page numbers usually go in the query string, the part of the URL after ?. Building it by gluing strings together breaks the moment a value contains a space, & or #. URLSearchParams does the encoding for you:
Press Run (⌘ Enter) to see what happens.What does this print?
const p = new URLSearchParams({ q: "fish & chips" });
console.log(p.toString());Auth headers and secrets
Most APIs need to know who is calling. After a user signs in, the server typically gives your app a token, a long random-looking string, and you send it on each request as a Bearer token:
const res = await fetch("/api/me", {
headers: { Authorization: `Bearer ${accessToken}` },
});"Bearer" means "whoever holds this is allowed in", so treat tokens like keys. That leads to the most important rule in this lesson: anything in frontend code is public. Every line of JavaScript you ship, every environment variable baked into the bundle (in Next.js, anything prefixed NEXT_PUBLIC_; in Vite, VITE_), can be read by anyone who opens DevTools. A user's own token is fine to hold in the browser because it only unlocks their data. Your company's secret keys (a payment provider's secret key, an AI API key, a database password) are not. Put them on a server, and have the browser call your server, which adds the key and forwards the request.
CORS from the browser's point of view
Sooner or later you will see this in the console: "has been blocked by CORS policy". Here is what is happening. By default the browser's same-origin policy stops a page from reading responses from a different origin (the scheme, host and port: https://shop.com and https://api.shop.com are different origins). CORS (Cross-Origin Resource Sharing) is how a server opts in: it replies with an Access-Control-Allow-Origin header naming the origins it trusts.
For "non-simple" requests (a JSON body, an Authorization header, methods like PUT or DELETE), the browser first sends a preflight: an automatic OPTIONS request asking permission.
Your page lives on https://app.example.com; the API is on https://api.example.com.
Three facts clear up most confusion. CORS is enforced by the browser, so the same request from curl or a server works fine. You fix it on the server (or by calling through your own backend), never with a frontend setting; mode: "no-cors" just gives you an empty response you cannot read. And CORS is not an auth system: it protects users' browsers, not your API.
Loading, error and empty states
Every screen backed by an API is in one of four states, and users notice when you forget one:
- Loading: show a spinner or skeleton, and disable the button that started it.
- Error: say what went wrong in plain words and offer a retry.
- Empty: success, but zero results. "No recipes match 'kale'" beats a blank page.
- Success: the data.
The little app below uses a fake fetch (the preview has no network) that returns real Response objects after a delay. Use the buttons to force each state:
Preview
Notice aria-live="polite": screen readers announce the text when it changes, so a blind user also hears "Loading" and then the result. Try changing the delay to 3000 and imagine waiting without the loading message.
Pagination
APIs rarely return 10,000 rows at once. They split results into pages. You will meet two styles:
- Offset (page number):
?page=3&limit=20. Easy, and lets users jump to page 7, but items can be skipped or repeated if rows are added while someone pages. - Cursor: the response includes
nextCursor, an opaque marker you send back as?cursor=...to get the next page. Stable under inserts and fast on huge tables; used by most large APIs. You cannot jump to page 7, which suits infinite scroll.
Press Run (⌘ Enter) to see what happens.In a real UI you would load one page at a time (a "Load more" button or infinite scroll) rather than everything at once.
Caching responses in memory
If three components ask for the same user within a second, sending three identical requests is waste. A small in-memory cache keyed by URL fixes it. The trick is to cache the promise, not the data: a second caller during the first request gets the same in-flight promise, so duplicates are merged. Add a time to live (TTL) so data does not go stale forever, and drop failures so a retry can try again:
Press Run (⌘ Enter) to see what happens.Four calls, two requests. Real apps usually reach for a library (TanStack Query, SWR, RTK Query) that adds invalidation after writes, background refresh and the stale-request handling from the previous lesson, but they are built on this same idea.
A typed API client in TypeScript
This section uses TypeScript, which has its own unit at the end of the course. If you have not reached it yet, skip ahead to the terms and come back later.
TypeScript lets you describe the shape you expect. But res.json() returns any at runtime: the server can send anything, and a type annotation does not check it. A good client does both: a type for your editor and a runtime check for reality.
export type Recipe = { id: number; title: string; minutes: number };
export class ApiError extends Error {
constructor(public status: number, message: string) {
super(message);
}
}
function isRecipe(value: unknown): value is Recipe {
if (typeof value !== "object" || value === null) return false;
const v = value as Record<string, unknown>;
return typeof v.id === "number" && typeof v.title === "string" && typeof v.minutes === "number";
}
type RequestOptions = Omit<RequestInit, "headers"> & { headers?: Record<string, string> };
async function request(path: string, init: RequestOptions = {}): Promise<unknown> {
const res = await fetch(`/api${path}`, {
...init,
headers: { Accept: "application/json", ...init.headers },
signal: init.signal ?? AbortSignal.timeout(8000),
});
if (!res.ok) throw new ApiError(res.status, `${init.method ?? "GET"} ${path} failed`);
return res.status === 204 ? null : res.json();
}
export async function listRecipes(query: { tag?: string; page?: number } = {}): Promise<Recipe[]> {
const params = new URLSearchParams();
if (query.tag) params.set("tag", query.tag);
if (query.page) params.set("page", String(query.page));
const data = await request(`/recipes?${params}`);
if (!Array.isArray(data) || !data.every(isRecipe)) {
throw new Error("Unexpected response shape from /recipes");
}
return data; // now truly Recipe[]
}The value is Recipe return type is a type guard (from the narrowing lessons): after data.every(isRecipe) passes, TypeScript knows data is Recipe[], and so do you. Throwing an ApiError with the status lets the UI choose the right state (401 to sign-in, 404 to "not found"). On bigger projects, a schema library such as Zod writes the type and the check from one definition; check its docs for the current API.
- REST
- A style of API built around resources at URLs, acted on with HTTP methods like GET, POST and DELETE.
- idempotent
- Safe to repeat: sending the request twice leaves the server as sending it once would.
- Bearer token
- A credential sent as
Authorization: Bearer <token>; whoever holds it gets access. - CORS
- Browser rule that lets a server allow other origins to read its responses, via Access-Control headers.
- preflight
- The automatic OPTIONS request a browser sends to ask permission before some cross-origin requests.
- cursor pagination
- Paging with an opaque marker from the previous response instead of a page number.
- type guard
- A function returning
value is Tthat checks a value at runtime and narrows its type.