An API client and a practice server
🏠The everyday picture
Before the real shop opens, staff practise with a dummy till that behaves like the real one. When the real till arrives, they already know how to use it.
📘What it really is
- Put all API calls in one module,
src/api.ts, so components never deal with addresses and headers directly:
const BASE = import.meta.env.VITE_API_URL ?? "http://localhost:3001";
export async function getEnquiries(): Promise<Enquiry[]> {
const res = await fetch(`${BASE}/enquiries`);
if (!res.ok) throw new Error(`Couldn't load enquiries (${res.status})`);
return res.json();
}
-
import.meta.env.VITE_API_URLreads a setting from a.envfile, so the address can differ on your computer and on the live site. In Vite, only variables starting withVITE_reach the browser, and everything that reaches the browser is public: never put secrets there (Module 25). -
json-server gives you a pretend REST API from a JSON file, for practice:
npx json-server db.json --port 3001
with db.json holding { "enquiries": [ ... ] }. It supports GET, POST, PATCH and DELETE.
- Later, only
api.tschanges when your real backend arrives.
🖱️Try it
Create db.json with your sample enquiries and start json-server. Open http://localhost:3001/enquiries in the
browser. Create src/api.ts with getEnquiries, getEnquiry(id), createEnquiry(data),
updateEnquiry(id, changes) and deleteEnquiry(id), each checking res.ok.
✅Quick check
Why keep every API call in one api.ts file?
Show the answer
Addresses, headers and error handling are in one place; switching to a new backend changes one file.
Can you put a payment secret key in VITE_PAYMENT_KEY?
Show the answer
No. VITE_ variables are built into the frontend, which anyone can read.
