Data Fetching & APIs in Next.js
Learn how real-world apps load, manage, and display dynamic data safely.
π What is an API?
API (Application Programming Interface) is a system that allows two different software applications to communicate with each other.
In simple words: API is the bridge between frontend (your UI) and backend (server/database).
π Real Life Examples
- Weather App β fetch weather data
- Amazon β fetch products & prices
- Instagram β fetch posts & comments
- Dashboard β fetch analytics data
const res = await fetch("/api/users");
const data = await res.json();
console.log(data);β‘ How Data Fetching Works
Data fetching means getting data from a server and showing it in your UI.
In Next.js (client side), we usually fetch data inside useEffect so it runs after the page loads.
useEffect(() => {
async function loadData() {
const res = await fetch("/api/data");
const data = await res.json();
setData(data);
}
loadData();
}, []);β³ Loading State (Very Important)
Loading state is used to show feedback while data is being fetched.
Without loading state, users may think your app is broken or frozen.
const [loading, setLoading] = useState(true);
if (loading) {
return <p>Loading...</p>;
}β Error Handling (Very Important)
APIs can fail due to internet issues, server problems, or wrong URLs.
So we must always handle errors properly in production apps.
try {
const res = await fetch("/api/users");
if (!res.ok) {
throw new Error("Request failed");
}
const data = await res.json();
} catch (error) {
console.error(error);
}π₯ Displaying API Data
After fetching data, we display it using map() function.
βοΈ Client vs Server Fetching
Client Side Fetching
Data is loaded in the browser after page loads. Good for dashboards and interactive apps.
Server Side Fetching
Data is loaded before page is shown. Good for SEO and fast initial load.
β Best Practices
- Always show loading state
- Always handle errors properly
- Keep API logic clean and reusable
- Donβt fetch unnecessary data
- Use TypeScript for safety
π§ Summary
APIs are the backbone of modern web apps. Understanding fetching, loading states, and error handling is essential for building real-world applications.