fetch Wrapper
fetch Wrapper: free step-by-step lesson with examples, common mistakes, and interview tips — part of MERN Stack Tutorial on Toolliyo Academy.
On this page
MERN Stack Tutorial · Lesson 51 of 100
fetch Wrapper
Setup & React ✓ → API Mongo Auth ✓ → Wire & Harden → Ship & Projects
Wire & Harden · 3 — Full stack · ~6 min · UI Meets API
What is this?
A small api(path, options) helper attaches the base URL and Authorization header so components stay clean.
Why should you care?
Scattered fetch calls duplicate error handling and forget tokens.
See it live — copy this example
Run examples in your MernVerse client/ (Vite React) or server/ (Express) folders. Keep secrets in .env.
const API = import.meta.env.VITE_API_URL;
export async function api(path, { token, ...opts } = {}) {
const res = await fetch(API + path, {
headers: {
'Content-Type': 'application/json',
...(token ? { Authorization: `Bearer ${token}` } : {})
},
...opts
});
if (!res.ok) throw new Error(await res.text());
return res.status === 204 ? null : res.json();
}
Run Example »
Edit the code below and click Run to see the result in Toolliyo’s live editor.
What happened?
- Use VITE_ env for the public API URL.
- Throw on !ok so UI can show errors.
- Skip JSON parse on 204.
Practice next
- Add VITE_API_URL=http://localhost:5000.
- Call api("/api/health").
- Pass token from auth context.
- Support FormData without forcing Content-Type.
- Add timeout with AbortController.
Remember
One client helper. Attach Bearer when present. Surface HTTP errors.
SPA talks API
Notes page loads list.
Outcome: One helper used everywhere.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!