Introduction: Connecting Your Frontend and Backend
Welcome to the first lesson of this course, where we will set up the API client for your project. In modern web applications, the frontend (what users see and interact with) often needs to communicate with the backend (where data and business logic live). In our case, the frontend is built with React, and the backend uses NestJS.
To make this communication possible, we use an API client. The API client is a set of functions that help your React app send requests to the backend and handle the responses. Setting up this client is the first step in allowing your app to fetch data, show updates, and interact with users in real time.
This lesson makes your React app capable of talking to the backend by creating a small, environment-aware API client and then verifying connectivity from HomePage. We will:
Define environment helpers and base URL candidates (isBrowser, isLocalhost, PORT_HOST, cachedBase, BASE_CANDIDATES) and explain them in depth.
Centralize endpoint paths in a paths helper.
Implement a tiny fetch-based apiClient and a hello() function that calls /api/hello.
Use useEffect in HomePage to test the API status and display a user-friendly indicator.
By the end, you’ll understand exactly how URLs are chosen, why we cache the base, how the /api/hello request works, and how HomePage safely updates state after an async call.
Breaking Down the API Client Code
Let’s look at the main parts of the API client, which lives in src/api/client.ts. Here is the code:
Centralized endpoint paths:paths.hello() returns the canonical string "/api/hello". Keeping paths in one object avoids typos and makes future refactors (e.g., prefix changes) a single-edit operation.
Hello call flow:hello() performs apiClient.get(paths.hello()), which sends a GET request to /api/hello. It logs successes for dev visibility, throws on errors to let the caller decide how to handle failures, and returns the parsed JSON (the backend “envelope”).
Expected envelope: For this endpoint, the backend replies with { success: true, data: "Hello World!" }. Your UI reads success (for status) and may read data (the string) for confirmation.
hello is an asynchronous function. It uses await to wait for the API response.
It calls apiClient.get(paths.hello()), which sends a GET request to /api/hello.
If the request is successful, it logs the response and returns it.
If there is an error (for example, if the server is down), it logs the error and throws it so the calling code can handle it.
Example output in the browser console:
Shell
API /api/hello response: { success: true, message: "Hello from the backend!" }
or, if there is an error:
Shell
Error calling /api/hello: Error: Network Error
This function is a simple example of how your frontend can talk to your backend using the API client.
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal
Using the API Client on the Home Page
Now, let’s see how the API client is used in the React frontend. Here is the relevant part of src/pages/HomePage.tsx:
The HomePage component uses React’s useState and useEffect hooks.
When the page loads, it calls the hello function from the API client.
If the backend responds with { success: true }, it sets the status to "Connected."
If there is an error or the response is not successful, it sets the status to "Connection Failed."
The status is displayed on the page, so users can see if the frontend is able to talk to the backend.
Example output on the page:
API Status: Connected
or
API Status: Connection Failed
This is a simple but powerful way to check if your frontend and backend are connected.
HomePage useEffect
Let's break down the usage of the useEffect hook we saw in the HomePage.tsx component.
State Setters (setServerStatus, setHelloMessage)
useState returns a getter and a setter. Calling a setter schedules a re-render with the new value.
We initialize serverStatus to "Checking..." so the UI communicates that a health check is in progress.
When a response arrives, we flip it to "Connected" or "Connection Failed". If we receive a greeting string in data, we store it in helloMessage.
The Effect Lifecycle
The effect runs once after the first render because the dependency array is [].
Inside the effect, we call hello() which returns a promise resolving to ApiEnvelope<string>.
When the promise resolves successfully, we extractsuccess and data from the envelope. This mirrors the backend’s global response contract.
If success is true, the server is reachable and responded as expected. If false, we treat it as a connectivity or health failure for the purpose of this check.
isMounted Guard
let isMounted = true; is a safety flag to avoid setting state after the component unmounts.
Why needed: async promises may resolve after a route change or rapid navigation. Updating state on an unmounted component leads to React warnings and is wasted work.
We check if (!isMounted) return; inside both .then and .catch.
The cleanup functionreturn () => { isMounted = false; } runs automatically on unmount (and before the effect re-runs, if it had dependencies). This makes late promise resolutions no-ops.
The catch Block
Catches network errors, CORS issues, JSON parsing errors, or any thrown exceptions in the chain.
We still guard with isMounted and then set the status to "Connection Failed" to show a clear user-facing signal.
Optional logging (commented) can help diagnose issues during development without spamming the console in production.
Extracting Success from the Backend
We treat the backend response as ApiEnvelope<HelloData>. The fields of interest are success and data.
Reading success standardizes how we interpret results across endpoints. For /api/hello, a healthy response is { success: true, data: "Hello World!" }.
Storing the data string in helloMessage is optional but helpful; it confirms that not only did the request succeed, but the payload is exactly what we expected.
Why This Structure Works
Environment helpers make URLs portable across local dev, sandboxed ports, and same-origin reverse proxies.
A shared paths object removes stringly-typed endpoints and helps avoid typos.
Returning the envelope from hello() keeps the calling UI consistent with other endpoints that will be added later.
The useEffect pattern with an isMounted guard is robust for small health checks and scales to more complex data fetching where cancellation or staleness matters.
With this foundation, your frontend speaks reliably to the backend and communicates status clearly to users and developers. Next, you can build additional client helpers (auth, books, shelf) using the same envelope pattern and paths registry.
Deep Dive: Breaking Down the API Client Code
Deep Dive: The request<T>() pipeline (step-by-step)
Summary and What’s Next
In this lesson, you learned how to set up an API client to connect your React frontend to your NestJS backend. We covered:
Why an API client is important
How the client code detects the environment and chooses the right base URL
How to make a simple API call to the backend
How to use the API client in a React component to show the connection status
You are now ready to practice making and using API calls in your own code. In the next exercises, you will get hands-on experience with these concepts, helping you build confidence in connecting your frontend and backend.
Let's review our apiClient code and understand what it does. We'll start with Environment Detection.
Note: This is a deep dive section: it explains why the code is structured the way it is, how environment detection works, and how requests are retried across base URLs.
Understanding this is valuable for debugging and scaling later, but it’s not mandatory — you can skim it now and return later if something breaks.
These lines check if the code is running in a browser and if it’s running on your local machine. This helps the client know how to build the correct URL for API requests.
isBrowser
Checks typeof window !== 'undefined'.
Why: In SSR/tests, window doesn’t exist. This flag prevents accidental use of browser-only APIs and lets you adapt URL building to the runtime.
isLocalhost
Verifies the hostname is exactly localhost or 127.0.0.1.
Why: During local development, your backend often runs at a known port (e.g., 3001). Recognizing localhost lets you target http://localhost:3001 directly.
Here, the code sets up possible base URLs for the API. If you are running locally, it uses http://localhost:3001. If you are running in another environment, it tries other options. This makes the client flexible and able to work in different setups.
PORT_HOST
Computes an alternative host like https://<first-label>-3001.<rest> from the current hostname.
Why: Many sandboxes/platforms can’t expose :3001 directly but do expose it through a subdomain pattern (e.g., myapp-3001.example.com). This string gives us a fallback to reach the backend.
cachedBase
A module-level variable that starts as null and stores the first chosen base URL.
Why: Picking the base once avoids recomputing logic on every request and ensures consistent origins during a session.
BASE_CANDIDATES
An ordered list of potential base URLs.
Localhost flow:['http://localhost:3001'] (explicit port for a dev server).
Browser non-local flow:['', PORT_HOST]. The empty string means relative URLs so requests go same-origin (ideal when a reverse proxy forwards /api to the backend). If that isn’t available, PORT_HOST is the next best guess.
Non-browser flow:[''] so server-side or tests resolve to relative paths and can be adapted by the environment.
This object helps you build the correct path for each API endpoint. For example, paths.hello() returns /api/hello.
Why: Keeps paths consistent in one place; changing the route in the future requires a single edit, reduces typos, and makes code self-documenting.
This setup makes it easy to write code that works both locally and in production, without having to change URLs by hand.
Note: This section is another deep dive into how our generic request function works under the hood.
While it’s useful to understand each stage (headers, candidate URLs, parsing, error handling), you don’t need to memorize all the details to use the API client effectively.
Think of this as "peeking behind the curtain" — a great way to build intuition, but optional if you just want to focus on building features.
TypeScript
export async function request<T = any>( path: string, init: RequestInit = {}): Promise<T> { const headers: Record<string, string> = { ...(init.body ? { 'Content-Type': 'application/json' } : {}), ...(init.headers as Record<string, string> | undefined), }; const bases = cachedBase ? [cachedBase] : BASE_CANDIDATES; let lastErr: any = null; for (const base of bases) { const url = `${base}${path}`; try { const res = await fetch(url, { ...init, headers, mode: 'cors' }); const text = await res.text(); const data = text ? (() => { try { return JSON.parse(text); } catch { return text; } })() : null; if (!res.ok) { lastErr = Object.assign(new Error('Request failed'), { status: res.status, data, }); if ( !cachedBase && (res.status === 404 || res.status === 502 || res.status === 0) ) { continue; // try next base } throw lastErr; } if (!cachedBase) cachedBase = base; return data as T; } catch (e: any) { lastErr = e; continue; } } throw lastErr || new Error('All base URLs failed');}
Headers assembly:
Adds Content-Type: application/jsononly when a body exists; merges user-supplied headers. Keeps GET requests lean and standards-compliant.
Candidate loop:
Uses cachedBase if known; otherwise iterates BASE_CANDIDATES. Builds url = base + path and performs fetch(url, { ...init, headers, mode: 'cors' }).
Response parsing:
Reads res.text() and then attempts JSON parse. If parsing fails, returns raw text. This gracefully handles text or JSON envelopes.
HTTP error handling:
When !res.ok, creates an Error with status and parsed data.
If we haven’t cached a base yet and the status is 404 / 502 / 0, we try the next base (e.g., reverse proxy isn’t wired, but the port-mapped host works). Otherwise, we throw immediately.
Successful response & base memoization:
On success, if no cachedBase exists, we memoize the current base to speed up subsequent calls.
Final failure:
If all candidates fail, we throw the last captured error (or a generic error).
The apiClient facade
apiClient.get<T>(path)
A typed wrapper around request<T>() for GETs.
Usage from client.ts: apiClient.get(paths.hello()) → returns the parsed body (e.g., { success: true, data: "Hello World!" }).