Practical API Tutorial
How to Simulate Slow API Responses and Test Loading States
Fast local APIs hide loading problems: flickering spinners, screens that never time out, and search results that arrive in the wrong order. Slow your API down on purpose and fix them before your users find them.
Steps 1 to 6 work on any plan. Hosted response delays need a paid Forge API plan.
What we are building
A product search that stays usable when the API is slow
You will build a React search box that shows a skeleton only when a response is actually slow, tells the user when it is taking longer than usual, gives up after a timeout, and never shows results for an older query. Then you will test each of those behaviours.
The search calls a hosted endpoint such as /search. Forge API does not read query strings, so ?q=cat and ?q=ca return the same JSON. That is fine here: this tutorial is about timing, not search results.
Slow it down
Choose how to slow down the response
Each method suits a different job. You will usually combine them: throttling for a quick look, a helper or route delay for repeatable tests, and a hosted delay when other devices need the same slow API.
| Method | Plan | What it slows | Good for |
|---|---|---|---|
| Browser network throttling | Any plan | The whole page, while you test by hand | Quick manual checks |
| A development delay helper | Any plan | Requests made through your helper | Repeatable delays while you build |
| Playwright route delays | Any plan | Requests in automated browser tests | Loading and timeout tests in CI |
| Forge API response delay | Paid plans | One hosted endpoint, for every device and teammate | Mobile apps, demos and QA on a shared URL |
Browser throttling is in the Network panel of your browser's developer tools. It slows every request on the page, including scripts and images, so it is the most realistic quick check.
Delay helper
Add a development-only delay
A small helper lets you slow down specific requests while you build. The delay respects an abort signal, so cancelled requests stop waiting immediately. Read the delay from an environment variable and leave it at zero in production builds.
// src/lib/devDelay.ts
/** Waits for `ms` milliseconds, and stops early if the signal is aborted. */
export function sleep(ms: number, signal?: AbortSignal): Promise<void> {
return new Promise((resolve, reject) => {
if (signal?.aborted) return reject(signal.reason);
const timer = setTimeout(resolve, ms);
signal?.addEventListener(
"abort",
() => {
clearTimeout(timer);
reject(signal.reason);
},
{ once: true },
);
});
}
/**
* Adds an artificial delay before a request during development only.
* Set the value from an environment variable, never in production builds.
*/
export async function fetchWithDevDelay(
input: string,
init: RequestInit & { devDelayMs?: number } = {},
) {
const { devDelayMs = 0, ...rest } = init;
if (devDelayMs > 0) await sleep(devDelayMs, rest.signal ?? undefined);
return fetch(input, rest);
}Loading states
Show loading states without flicker
A spinner that appears for 50 milliseconds looks like a glitch. Show loading UI only when the request is actually slow, and add a second, later message so the user knows the app has not frozen.
// src/lib/useDelayedFlag.ts
import { useEffect, useState } from "react";
/**
* Returns true only after `active` has stayed true for `delayMs`.
* Fast responses never flash a spinner or skeleton.
*/
export function useDelayedFlag(active: boolean, delayMs: number) {
const [visible, setVisible] = useState(false);
useEffect(() => {
if (!active) {
setVisible(false);
return;
}
const timer = setTimeout(() => setVisible(true), delayMs);
return () => clearTimeout(timer);
}, [active, delayMs]);
return active && visible;
}- Skeletons suit content with a known shape, such as lists and cards. They reduce layout shift when the data arrives.
- Spinners suit actions without a predictable layout, such as saving a form.
- Mark the region with
aria-busyand announce text changes with a polite live region. Respectprefers-reduced-motionin skeleton animations.
.skeleton-row {
height: 1rem;
margin-block: 0.75rem;
border-radius: 0.25rem;
background: #e5e7eb;
}
@media (prefers-reduced-motion: no-preference) {
.skeleton-row {
animation: skeleton-pulse 1.5s ease-in-out infinite;
}
}
@keyframes skeleton-pulse {
50% {
opacity: 0.5;
}
}Timeouts
Give up after a timeout
fetch has no default timeout, so a request that hangs can keep a screen loading indefinitely. AbortSignal.timeout() aborts after a set time, and AbortSignal.any()combines it with the caller's own signal so both can cancel the request.
// src/lib/fetchWithTimeout.ts
const API_BASE_URL = "https://apis.getforgeapi.com/YOUR_PROJECT_KEY";
export class TimeoutError extends Error {
constructor(ms: number) {
super(`The request took longer than ${ms / 1000} seconds.`);
this.name = "TimeoutError";
}
}
export async function getJson<T>(
path: string,
{ timeoutMs = 8000, signal }: { timeoutMs?: number; signal?: AbortSignal } = {},
): Promise<T> {
const timeoutSignal = AbortSignal.timeout(timeoutMs);
// Abort on whichever happens first: the timeout or the caller cancelling.
const combined = signal
? AbortSignal.any([signal, timeoutSignal])
: timeoutSignal;
try {
const response = await fetch(`${API_BASE_URL}${path}`, {
signal: combined,
});
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return (await response.json()) as T;
} catch (error) {
if (timeoutSignal.aborted && !signal?.aborted) {
throw new TimeoutError(timeoutMs);
}
throw error;
}
}Browser support
AbortSignal.any() is newer than AbortSignal.timeout(). Check your browser support targets, and fall back to a single AbortController with setTimeout if you support older browsers.
Race conditions
Cancel stale requests
Responses do not always arrive in the order you sent them. If the request for "ca" is slower than the request for "cat", it finishes last and replaces the newer results. Creating an AbortControllerper query and aborting it in the effect's cleanup fixes this, and also cancels the request when the component unmounts.
// src/components/ProductSearch.tsx
import { useEffect, useState } from "react";
import { getJson, TimeoutError } from "../lib/fetchWithTimeout";
import { useDelayedFlag } from "../lib/useDelayedFlag";
type Product = { id: number; name: string };
type State =
| { status: "idle" }
| { status: "loading" }
| { status: "ready"; products: Product[] }
| { status: "error"; message: string };
export function ProductSearch({ path = "/search" }: { path?: string }) {
const [query, setQuery] = useState("");
const [state, setState] = useState<State>({ status: "idle" });
useEffect(() => {
if (!query) {
setState({ status: "idle" });
return;
}
// One controller per query: typing again cancels the older request,
// so a slow response for "ca" can never replace results for "cat".
const controller = new AbortController();
setState({ status: "loading" });
getJson<Product[]>(`${path}?q=${encodeURIComponent(query)}`, {
signal: controller.signal,
timeoutMs: 8000,
})
.then((products) => setState({ status: "ready", products }))
.catch((error: unknown) => {
if (controller.signal.aborted) return; // replaced or unmounted
setState({
status: "error",
message:
error instanceof TimeoutError
? "Search is taking too long. Please try again."
: "Search failed. Please try again.",
});
});
return () => controller.abort();
}, [query, path]);
const loading = state.status === "loading";
const showSkeleton = useDelayedFlag(loading, 200);
const showSlowMessage = useDelayedFlag(loading, 4000);
return (
<div>
<label htmlFor="search">Search products</label>
<input
id="search"
value={query}
onChange={(event) => setQuery(event.target.value)}
/>
<div aria-busy={loading} aria-live="polite">
{showSkeleton ? (
<ul data-testid="results-skeleton" aria-hidden="true">
<li className="skeleton-row" />
<li className="skeleton-row" />
<li className="skeleton-row" />
</ul>
) : null}
{showSlowMessage ? <p role="status">Still loading…</p> : null}
{state.status === "ready" ? (
<ul aria-label="Search results">
{state.products.map((product) => (
<li key={product.id}>{product.name}</li>
))}
</ul>
) : null}
{state.status === "error" ? (
<p role="alert">{state.message}</p>
) : null}
</div>
</div>
);
}To reproduce the race on purpose, use the development delay helper with a longer delay for shorter queries, or a random delay for each request. A hosted delay will not do it: every request goes to the same path and waits the same fixed time, so the responses arrive in order.
Automate it
Test loading states with Playwright
page.route can hold a request before letting it through, which makes the skeleton visible long enough to assert on. A route that never answers tests the timeout path.
// tests/loading.spec.ts (Playwright)
import { expect, test } from "@playwright/test";
test("shows a skeleton while search results load", async ({ page }) => {
// Hold every search request for 2 seconds before letting it through.
await page.route("**/search?*", async (route) => {
await new Promise((resolve) => setTimeout(resolve, 2000));
await route.continue();
});
await page.goto("/products");
await page.getByLabel("Search products").fill("headphones");
await expect(page.getByTestId("results-skeleton")).toBeVisible();
await expect(page.getByRole("list", { name: "Search results" })).toBeVisible();
});
test("shows an error when the request times out", async ({ page }) => {
// Never answer, so the app's 8-second timeout fires.
await page.route("**/search?*", () => {});
await page.goto("/products");
await page.getByLabel("Search products").fill("headphones");
await expect(page.getByRole("alert")).toHaveText(/taking too long/, {
timeout: 10_000,
});
});Keep these tests fast
Use the shortest delay that still makes the loading state visible. For the timeout test, consider making the timeout configurable so tests can use a lower value.
Hosted delays
Use a Forge API response delay
On paid plans, each endpoint can wait before responding. Because the delay is on the server, every client sees it: a phone on mobile data, a teammate's laptop, or a demo in front of a client. The maximum delay depends on your plan; the API limits page explains plan features.
Set the delay in the endpoint settings, then check it with curl:
curl -s -o /dev/null \
-w "Status %{http_code}, total %{time_total}s\n" \
https://apis.getforgeapi.com/YOUR_PROJECT_KEY/search-slowDelays count like any other request
A delayed request still counts once towards your monthly allowance. See Endpoints for how response delays are configured.
Limits
What this approach does not cover
- A fixed delay is not real network variability. Throttling in the browser is closer to a slow mobile connection.
- A hosted endpoint returns the same response each time, so it cannot be slow once and fast the next time. Use different paths, or an in-process mock such as MSW, for sequences.
- Delays test your frontend, not your backend's performance.
Once loading states work, handle the failures too: How to Test API Error Responses in Your Frontend.
Frequently asked questions
Simulating slow API responses
How do I simulate a slow API response?
Use your browser's network throttling for quick manual checks, add a development-only delay in your fetch helper, or delay requests in Playwright with page.route. On paid Forge API plans you can also add a response delay to a hosted endpoint, so every device that calls it sees the same slow response.
Should I show a spinner or a skeleton?
Use a skeleton when you know the shape of the content, such as a list or a card, because it reduces layout shift. Use a spinner for actions with no predictable layout, such as saving a form. In both cases, wait about 200 milliseconds before showing it so fast responses do not flicker.
How long should a request timeout be?
There is no single right value. Base it on how long a normal response takes and how long a user will reasonably wait on that screen. This tutorial uses 8 seconds as an example, and shows a still-loading message after 4 seconds so the user is told well before the request gives up.
Does Forge API support response delays on the Free plan?
No. Custom response delays are available on paid plans, and the maximum delay depends on the plan. Everything else in this tutorial works without a Forge API delay.
Why do old search results sometimes replace new ones?
Responses can arrive in a different order from the requests. If the request for "ca" is slower than the request for "cat", it finishes last and overwrites the newer results. Cancel the previous request with an AbortController whenever a new one starts.
Build against a hosted API
Create mock endpoints with your own JSON, then test loading, timeout and error states against a real HTTPS URL.