Calling the API from the client
One thin, typed layer between your components and fetch: a base URL, credentials, a single error type, and why components should not call fetch themselves.
End-to-end type safetyError handling across the stackCORS and cross-origin setups
Calling the API from the client
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- fetch returns a promise that resolves for a 404 or 500, so a bare fetch call never throws on an error status and you must check res.ok yourself.
- A single API module that owns the base URL, credentials and error conversion keeps those decisions out of every component.
- Converting every failure into one ApiFailure class lets components branch on status and code instead of parsing response bodies.
- Model request state as a discriminated union of loading, error and success, so TypeScript stops you from reading data that is not there yet.
- Components should call named functions such as getBoard, not fetch, which makes the calls easy to mock in tests and easy to move behind a data-fetching library.
The bare fetch trap
Here is the call most tutorials show:
const res = await fetch("/api/projects/1/board");
const board = await res.json();
Two things are wrong with it. First, fetch only rejects if the request could not be made at all: no connection, a CORS refusal. A 404 or 500 is a successful round trip as far as fetch is concerned, so res.json() happily parses your error body and board is now an error object typed as a board. Second, res.json() returns any, so TypeScript stops helping at exactly the boundary where you need it. The fetch and working with APIs lesson covers the mechanics; this one is about where the call lives.
If every component repeats fetch, each one decides separately about the base URL, cookies, headers and failures. Some will forget. The bug appears in the one screen nobody tested.
One module owns the wire
The fix is a thin layer between components and the network. In Taskboard it has two small parts. The first is the typed caller from the end-to-end types lesson, with the base URL in one place:
export const api = hc<AppType>(import.meta.env.VITE_API_URL ?? "", {
init: { credentials: "include" },
});
The second converts any failure into the one error class from error handling across the stack:
export async function unwrap<T>(res: Response & { json(): Promise<T> }): Promise<T> {
if (res.ok) return res.status === 204 ? (undefined as T) : res.json();
const body = (await res.json().catch(() => null)) as any;
throw new ApiFailure(res.status, body?.error?.code ?? "unknown",
body?.error?.message ?? res.statusText, body?.error?.fields);
}
Then components never see fetch. They see named functions:
export const getBoard = async (id: number) =>
unwrap(await api.api.projects[":id"].board.$get({ param: { id: String(id) } }));
That snippet type-checks with the compiler. I ran the same layer from a Node script against the live API. A signed-in caller got the board with its typed counts, an empty title raised ApiFailure with 422 validation { title: ['Give the task a title'] }, and an unknown project raised 404 not_found. Everything the UI will need to branch on arrived as a typed value.
The credentials: "include" line is the other half of the cookie story from CORS and cross-origin setups. Put it in one place and no call can forget it.
Why named functions beat inline calls
A function called getBoard is a seam. You get three things from it:
- Tests. In a component test you replace
getBoardwith a stub. You cannot cleanly stub afetchburied in a component without patching globals. - Refactors. When the endpoint moves or its shape changes, the compiler points at the one function and its callers.
- A path to caching. The moment you add TanStack Query,
getBoardbecomes thequeryFn, and the components change very little. The next group builds this.
Keep the layer thin. It should translate, not decide. Retry rules, caching and “which screen is loading” belong elsewhere.
Model request state honestly
Without a library you may still hold state yourself. The mistake to avoid is three booleans:
const [loading, setLoading] = useState(true);
const [error, setError] = useState<ApiFailure | null>(null);
const [data, setData] = useState<Board | null>(null);
That allows eight combinations, and only three make sense. loading: false, error: null, data: null is a bug that compiles. Use one value whose shape depends on its status:
type Remote<T> =
| { status: "loading" }
| { status: "error"; error: ApiFailure }
| { status: "success"; data: T };
Now if (state.status === "success") narrows data to a real Board, and reading it in the other branches is a type error. This is the same union you will see as status in TanStack Query’s result.
Cancellation and races
Two details bite later. A user clicks project A, then project B, and the response for A arrives last and overwrites B. Pass an AbortSignal from the effect’s cleanup, and the stale call is cancelled; the cleanup and race conditions in effects lesson shows the pattern. Second, decide a timeout, because a fetch with none can hang for minutes on a bad connection.
Both are reasons to reach for a data-fetching library before you reach a hundred hand-rolled calls. The case for a data-fetching library lays out what it removes, and TanStack Query fundamentals teaches the tool itself.
A checklist for the client layer
- One module knows the base URL. It comes from configuration, not a literal.
- Credentials are set once.
- A non-OK response always throws the same error class.
- A failed network call is distinguishable from a server error.
- Responses are typed from the server, not retyped by hand.
- Components call named functions.
What the video covers
Codepoint’s “Stop Typing fetch() as any — Generic API Wrapper in TypeScript” is about six and a half minutes, published August 2026. Its chapters cover why fetch returns any, defining a response interface, building a generic fetch wrapper, handling loading, error and success state, and a single discriminated union type. That matches the second half of this lesson closely. It types responses by hand, whereas this lesson derives them from the server; treat the video as the mechanism and the previous lessons as the source of truth. I could not read a transcript. PedroTech’s TanStack Query course is linked as the longer next step.
Where this fits
The API contract is now complete: endpoints shaped for screens, types derived from the server, validation on both sides, one error shape, CORS settled, and a thin client layer. The next group puts a person behind the requests. Next: the sign-up and login flow.
Check yourself
Why does fetch not throw on a 404?
The promise only rejects when the request could not be completed at all, so an HTTP error status still resolves and you have to test res.ok.
What does the typed client in Taskboard return when the server answers 422?
The unwrap helper throws an ApiFailure with status 422, code validation and the fields map, which a form can display directly.
Why put the base URL and credentials in one module?
They change between environments and apply to every call, so one place to change them avoids missing a call and sending it cross-origin without cookies.
Why use a discriminated union for loading, error and success?
It makes the states mutually exclusive, so TypeScript narrows on the status and refuses to let you read data while the request is still loading or has failed.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.