Working with REST APIs in Production
Structure an API layer with typed clients, authentication, error handling, pagination and CORS awareness.
Intermediate · about 5 hours · difficulty 3/5
Learn first: Server State with TanStack Query, TypeScript Fundamentals
Calling fetch in a component is fine for a demo. Real apps need a consistent way to talk to a backend so auth, errors and types are handled once, not in every component.
Build an API layer
- A small client module wraps fetch (or a library like
kyoraxios): it sets the base URL from an environment variable, adds auth headers or sends cookies withcredentials: "include", parses JSON and throws a typed error for non-2xx responses (remember:fetchdoes not reject on 404 or 500). - One function per endpoint:
getProducts(params),createOrder(body). Components and query hooks call these, never raw URLs. - Validate responses at the boundary with a schema (Zod) or generate types from an OpenAPI spec so frontend and backend agree.
Everyday concerns
- REST conventions: resources, HTTP methods, status codes and query parameters for filtering, sorting and pagination (offset or cursor based).
- Errors: distinguish network failures, validation errors (show them next to fields), auth errors (redirect to login) and server errors (friendly message plus retry).
- Auth flows: refresh an expired session transparently once, then log out if refresh fails.
- CORS: the browser blocks cross-origin responses unless the server allows your origin. It is fixed on the server or with a dev proxy, never by a frontend flag.
- Mocking: use MSW (Mock Service Worker) to develop and test against fake endpoints before the backend is ready.
Good enough to move on
You have a typed API module with central error handling, environment-based base URL and auth, used through query hooks, plus mocks for local development.
Key concepts
- REST resources, methods and status codes
- A typed API client module
- Central error handling
- Auth headers, cookies and token refresh
- Pagination and filtering parameters
- CORS from the frontend's perspective
- OpenAPI type generation
- Mocking with MSW
Mini project
Create an api/ folder for a public API (or a mock with MSW): a base client with typed errors, endpoint functions validated with Zod, a 401 handler that redirects to login, and query hooks that use them.
Check yourself
Your fetch call to /api/orders returns 500 but no catch block runs. Why, and where should you fix it?