Next.js Data Fetching
Next.js data fetching is one of the first real skills you need after learning routing and components. In the App Router, most data loading happens on the server, inside components that can be async and use await. That means your database passwords and API keys stay on the server, and your users get HTML that already contains the data.
This tutorial shows you how to fetch data in an async Server Component, query a database safely, choose between sequential and parallel requests, and stream slow sections with Suspense. You will also see how to handle errors, type the response with TypeScript, and avoid the common traps that make pages feel slow.
If you have just finished Next.js Loading & Error Handling, you already know what a loading state looks like. Now you will learn where the data actually comes from. The ideas here also connect closely to Server vs Client Components, because where you fetch changes what you can do with the result.
What Is Next.js Data Fetching in the App Router?
Next.js data fetching is the process of loading data from an API, database, or file inside a Next.js application. In the App Router, you normally fetch inside a Server Component by making the component async and using await. The data is read on the server before the page is sent to the browser, so the first HTML already includes the content .
Here is the smallest useful example. It fetches a list of users and renders their names:
// app/users/page.tsx
type User = {
id: number;
name: string;
email: string;
};
export default async function UsersPage() {
const response = await fetch("https://jsonplaceholder.typicode.com/users");
const users: User[] = await response.json();
return (
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
When you open /users, the browser receives HTML that already contains the list. There is no loading spinner on the first visit, because the server waited for the data before finishing the page. This is the default mental model for data fetching in Next.js: the server does the waiting, and the browser gets the result.
Fetch Data in an Async Server Component
An async Server Component is a component that runs only on the server and is allowed to use await. You do not need a special hook or a useEffect call. You mark the function async, call fetch with await, and return JSX.
Using fetch and await
The fetch API is the browser and Node.js function for making HTTP requests. In a Server Component, you can use it directly. The response object has a json() method, and you should give the result a type so TypeScript can check it.
// app/users/page.tsx
type User = {
id: number;
name: string;
email: string;
};
export default async function UsersPage() {
const response = await fetch("https://jsonplaceholder.typicode.com/users");
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
const users: User[] = await response.json();
return (
<ul>
{users.map((user) => (
<li key={user.id}>
{user.name} ({user.email})
</li>
))}
</ul>
);
}
How it works: The component is async, so Next.js waits for the promise to resolve before rendering the JSX. The response.ok check catches HTTP errors such as 404 or 500 before you try to read the body. The type User[] tells TypeScript that users is an array of objects with id, name, and email. If the API returns a different shape, TypeScript will not catch it at runtime, so the type is a promise you make to yourself and your team.
Typing the response with TypeScript
TypeScript strict mode does not know what an API returns. You write the type yourself, based on the API documentation or the actual response. Do not use any. If you are unsure, define a type with the fields you use, and add a runtime check when the data is critical.
// lib/types.ts
export type User = {
id: number;
name: string;
email: string;
};
export function isUser(value: unknown): value is User {
if (typeof value !== "object" || value === null) return false;
const candidate = value as Record<string, unknown>;
return (
typeof candidate.id === "number" &&
typeof candidate.name === "string" &&
typeof candidate.email === "string"
);
}
With this helper, you can check the array after parsing. A full validation library is better for large projects, but the idea is the same: TypeScript types disappear at runtime, so a real check makes the type honest.
Database Queries in a Server Component
A database query in a Server Component is safe because the code never reaches the browser. Server Components run on the server, and Next.js removes their code from the client bundle. You can import your database client, use environment variables, and run SQL or ORM calls directly .
// app/posts/page.tsx
import { db } from "@/lib/db";
type Post = {
id: number;
title: string;
published: boolean;
};
export default async function PostsPage() {
const posts: Post[] = await db
.selectFrom("posts")
.select(["id", "title", "published"])
.where("published", "=", true)
.execute();
return (
<ul>
{posts.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
);
}
How it works: The database call happens on the server before the page is rendered. The browser never sees your database URL, password, or query. This is the biggest practical difference from the old Pages Router pattern, where beginners sometimes created an API route just to fetch data for a page. In the App Router, you can call the database directly from the component that needs the data .
Sequential vs Parallel Data Fetching
When a page needs more than one piece of data, the order of your await calls matters. Sequential fetching waits for one request to finish before starting the next. Parallel data fetching starts all independent requests at the same time with Promise.all. The difference can be the difference between a page that feels instant and one that feels stuck.
Sequential fetching (one after another)
// app/dashboard/page.tsx
type User = { id: number; name: string };
type Post = { id: number; title: string };
export default async function DashboardPage() {
const userResponse = await fetch("https://jsonplaceholder.typicode.com/users/1");
const user: User = await userResponse.json();
const postsResponse = await fetch("https://jsonplaceholder.typicode.com/posts?userId=1");
const posts: Post[] = await postsResponse.json();
return (
<div>
<h2>{user.name}</h2>
<p>{posts.length} posts</p>
</div>
);
}
Here, the second request does not start until the first one finishes. If each request takes 300 milliseconds, the page waits about 600 milliseconds. The requests do not depend on each other, so this waiting is unnecessary.
Parallel fetching with Promise.all
// app/dashboard/page.tsx
type User = { id: number; name: string };
type Post = { id: number; title: string };
export default async function DashboardPage() {
const [userResponse, postsResponse] = await Promise.all([
fetch("https://jsonplaceholder.typicode.com/users/1"),
fetch("https://jsonplaceholder.typicode.com/posts?userId=1"),
]);
const user: User = await userResponse.json();
const posts: Post[] = await postsResponse.json();
return (
<div>
<h2>{user.name}</h2>
<p>{posts.length} posts</p>
</div>
);
}
How it works: Promise.all takes an array of promises and returns a single promise that resolves when all of them finish. Both fetch calls start at almost the same time. If each request takes 300 milliseconds, the total wait is close to 300 milliseconds, not 600. Use parallel fetching when the requests do not need each other. Use sequential fetching only when the second request needs a value from the first, such as a user ID or a slug.
| Pattern | When to use it | Wait time | Example |
|---|---|---|---|
| Sequential | The second request needs data from the first | Adds up | Fetch artist, then fetch that artist's albums |
| Parallel with Promise.all | Requests are independent | Close to the slowest request | Fetch user profile and recent posts together |
Streaming Slow Parts with Suspense
Suspense is a React feature that lets you show a fallback UI while part of the page is still loading. In Next.js, you can use <Suspense> to stream a slow section without blocking the whole page. The fast parts appear immediately, and the slow part fills in when its data is ready .
// app/dashboard/page.tsx
import { Suspense } from "react";
type Post = { id: number; title: string };
async function RecentPosts() {
const response = await fetch("https://jsonplaceholder.typicode.com/posts?_limit=5");
const posts: Post[] = await response.json();
return (
<ul>
{posts.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
);
}
export default function DashboardPage() {
return (
<main>
<h1>Dashboard</h1>
<p>This text appears immediately.</p>
<Suspense fallback={<p>Loading recent posts...</p>}>
<RecentPosts />
</Suspense>
</main>
);
}
Browser shows: The heading and the sentence appear first. The fallback text Loading recent posts... appears in the list area. When the request finishes, the fallback is replaced by the list of posts. This is useful when one section is much slower than the rest, such as a recommendation widget or a third-party API call. You do not need to wrap every component in Suspense. Use it around the slow parts.
Fetching in Client Components and When to Avoid It
A Client Component is a component marked with "use client" that runs in the browser. You can fetch data there with useEffect or a library such as SWR or React Query, but it is usually not the first choice in the App Router .
// app/search/page.tsx
"use client";
import { useEffect, useState } from "react";
type User = { id: number; name: string };
export default function SearchPage() {
const [users, setUsers] = useState<User[]>([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
async function load() {
const response = await fetch("https://jsonplaceholder.typicode.com/users");
const data: User[] = await response.json();
setUsers(data);
setLoading(false);
}
load();
}, []);
if (loading) return <p>Loading...</p>
return (
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
Browser shows: First the page displays Loading.... Then the list appears after the browser makes the request. The user waits for JavaScript to load, then waits again for the data. This double wait is why client-side fetching feels slower on first visit.
When to avoid it: Do not fetch in a Client Component when the data can be fetched on the server. Server fetching gives you faster first paint, better SEO, and no API keys in the browser. Use client fetching for data that must update after user interaction, such as a live search box that calls an API as the user types. Even then, consider fetching the first result set on the server and hydrating it into the client component.
Error Handling for Failed Requests
A failed request can happen for many reasons: the API is down, the URL is wrong, or the user is offline. In a Server Component, an unhandled error stops the page from rendering. Next.js shows the nearest error.tsx boundary if you have one, or a generic error page if you do not.
// app/users/page.tsx
type User = { id: number; name: string };
export default async function UsersPage() {
const response = await fetch("https://jsonplaceholder.typicode.com/users");
if (!response.ok) {
throw new Error(`Failed to load users: ${response.status}`);
}
const users: User[] = await response.json();
return (
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
Error in production: If the request fails and there is no error.tsx file, the user sees a generic error page. If you add error.tsx in the same route segment, your custom error UI appears instead. The error message in the terminal looks like this: Error: Failed to load users: 500. Always check response.ok before calling response.json(), because a 500 response may return HTML or an empty body, and json() will throw a confusing parse error.
Are fetch Responses Cached by Default in Next.js?
No. In current Next.js versions, fetch requests are not cached by default. You must opt in with { cache: "force-cache" } if you want Next.js to store the response in its server-side cache . This is a change from older versions, where fetch was cached automatically. The official Next.js documentation on nextjs.org/docs is the best place to confirm the current default for your exact version.
// app/stats/page.tsx
type Stats = { totalUsers: number };
export default async function StatsPage() {
const response = await fetch("https://jsonplaceholder.typicode.com/users", {
cache: "force-cache",
});
const users: Stats[] = await response.json();
return <p>Total users: {users.length}</p>;
}
How it works: Without the cache option, Next.js fetches fresh data when the route is rendered dynamically. With force-cache, Next.js looks for a matching request in its cache and returns the stored response if it is fresh. Only responses with a 200 status code are cached. If you need to refresh cached data on a schedule, use the next.revalidate option with a number of seconds.
Common Mistakes and Best Practices
- Awaiting requests that could run in parallel. If two requests do not depend on each other, sequential
awaitcalls double your wait time. UsePromise.allwhen the data is independent. - Forgetting to check
response.ok. Afetchcall does not reject on HTTP errors like404or500. It only rejects on network failures. If you skip the check,response.json()may throw a confusing error or return an error object that your UI tries to render. - Fetching user-specific data in a cached function without a user key. If you add caching later, make sure the cache key includes the user ID or session. Otherwise, one user's data can be served to another user.
- Using
anyfor API responses.anyturns off TypeScript's checks. Define a type, even a small one, so your editor and build step can catch mistakes such as readinguser.naminstead ofuser.name. - Wrapping the whole page in Suspense. Suspense works best around slow sections, not the entire page. If everything is inside one boundary, the user still waits for the slowest part before seeing anything.
- Fetching in a Client Component when the server could do it. Server fetching avoids the extra JavaScript load and the second network request from the browser. Use client fetching only when the data must change after user interaction.
Real-World Example
This example combines the main ideas: a typed response, two independent requests with Promise.all, and a Suspense boundary around a slower section. It is a small user dashboard page.
// app/dashboard/page.tsx
import { Suspense } from "react";
type User = {
id: number;
name: string;
email: string;
};
type Post = {
id: number;
title: string;
};
async function UserProfile() {
const response = await fetch("https://jsonplaceholder.typicode.com/users/1");
if (!response.ok) {
throw new Error("Could not load user");
}
const user: User = await response.json();
return (
<section>
<h2>{user.name}</h2>
<p>{user.email}</p>
</section>
);
}
async function UserPosts() {
const response = await fetch("https://jsonplaceholder.typicode.com/posts?userId=1");
if (!response.ok) {
throw new Error("Could not load posts");
}
const posts: Post[] = await response.json();
return (
<ul>
{posts.slice(0, 5).map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
);
}
export default async function DashboardPage() {
const [user, posts] = await Promise.all([
fetch("https://jsonplaceholder.typicode.com/users/1").then((r) => r.json() as Promise<User>),
fetch("https://jsonplaceholder.typicode.com/posts?userId=1").then((r) => r.json() as Promise<Post[]>),
]);
return (
<main>
<h1>Dashboard for {user.name}</h1>
<p>You have {posts.length} posts.</p>
<Suspense fallback={<p>Loading profile...</p>}>
<UserProfile />
</Suspense>
<Suspense fallback={<p>Loading posts...</p>}>
<UserPosts />
</Suspense>
</main>
);
}
Line-by-line explanation:
UserandPostare the TypeScript types for the two API responses. They match the fields the page uses.UserProfileandUserPostsare small async Server Components. Each one fetches its own data and checksresponse.okbefore parsing.DashboardPageis also async. It usesPromise.allto start both fetches at the same time. The result is an array with the user and the posts.- The page renders the user's name and post count immediately, using the data from
Promise.all. - The two
<Suspense>boundaries wrap the smaller components. In this version, the data is already available from the parallel fetch, so the fallbacks may not appear. In a real app, you would remove the duplicate fetches and let the Suspense boundaries handle the slow parts independently.
Summary
- Next.js data fetching usually happens in async Server Components. Mark the component
async, useawait fetch, and type the result. - Database queries in a Server Component are safe because the code never reaches the browser.
- Use
Promise.allfor independent requests. Use sequentialawaitonly when the second request needs the first request's result. Suspenselets you stream slow sections without blocking the rest of the page.fetchresponses are not cached by default in current Next.js. Opt in withcache: "force-cache"and check the official docs for your version.- Always check
response.okbefore callingresponse.json(), and avoid client-side fetching when the server can do the work.
When you need to create an API endpoint for your own data, continue with Next.js Route Handlers (API) to learn how to build request handlers in the App Router.
Frequently Asked Questions
What is the default caching behavior of fetch in Next.js?
In current Next.js versions, fetch requests are not cached by default. You must opt in by setting the cache option to force-cache. This gives you explicit control over what gets stored on the server. Older versions cached fetch automatically, so always check the documentation for your exact version .
Can I use async/await directly inside a Server Component?
Yes. Server Components can be async functions, and you can use await inside them. This is the recommended way to fetch data in the App Router. The component waits for the promise to resolve on the server, and the browser receives the finished HTML .
Should I use Promise.all or separate await calls?
Use Promise.all when the requests are independent and do not need each other's results. It starts all requests at the same time, so the total wait is close to the slowest single request. Use separate await calls only when the second request needs a value from the first, such as an ID or a slug.
When should I fetch data in a Client Component instead of a Server Component?
Fetch in a Client Component only when the data must update after user interaction, such as a live search field or a button that refreshes a list. For initial page data, a Server Component is usually better because it avoids extra JavaScript and a second network request from the browser.
How do I handle a failed fetch request in Next.js?
Check response.ok after the fetch call. If it is false, throw an Error with the status code. In a Server Component, this error will be caught by the nearest error.tsx boundary if one exists. Without a boundary, the user sees a generic error page. Checking response.ok also prevents confusing JSON parse errors.
Practice Exercises
Easy: Fetch and display a single user
Create a page at app/user/[id]/page.tsx that fetches a user from https://jsonplaceholder.typicode.com/users/1 and displays the name and email. Use a typed response and check response.ok.
Show solution
// app/user/[id]/page.tsx
type User = {
id: number;
name: string;
email: string;
};
export default async function UserPage() {
const response = await fetch("https://jsonplaceholder.typicode.com/users/1");
if (!response.ok) {
throw new Error("Failed to load user");
}
const user: User = await response.json();
return (
<div>
<h2>{user.name}</h2>
<p>{user.email}</p>
</div>
);
}
The component is async, checks the status, and renders typed fields.
Easy: Add a Suspense fallback
Wrap a slow component that fetches posts from https://jsonplaceholder.typicode.com/posts?_limit=3 in a <Suspense> boundary with a fallback that says Loading posts....
Show solution
// app/posts/page.tsx
import { Suspense } from "react";
type Post = { id: number; title: string };
async function Posts() {
const response = await fetch("https://jsonplaceholder.typicode.com/posts?_limit=3");
const posts: Post[] = await response.json();
return (
<ul>
{posts.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
);
}
export default function PostsPage() {
return (
<main>
<h1>Posts</h1>
<Suspense fallback={<p>Loading posts...</p>}>
<Posts />
</Suspense>
</main>
);
}
The Suspense boundary shows the fallback while the async child component waits for data.
Medium: Use Promise.all for two requests
Fetch a user and their posts at the same time. The user URL is https://jsonplaceholder.typicode.com/users/1 and the posts URL is https://jsonplaceholder.typicode.com/posts?userId=1. Display the user's name and the number of posts.
Show solution
// app/profile/page.tsx
type User = { id: number; name: string };
type Post = { id: number; title: string };
export default async function ProfilePage() {
const [userResponse, postsResponse] = await Promise.all([
fetch("https://jsonplaceholder.typicode.com/users/1"),
fetch("https://jsonplaceholder.typicode.com/posts?userId=1"),
]);
const user: User = await userResponse.json();
const posts: Post[] = await postsResponse.json();
return (
<div>
<h2>{user.name}</h2>
<p>{posts.length} posts</p>
</div>
);
}
Promise.all starts both fetches together, so the wait is shorter than sequential awaits.
Challenge: Add error handling and a retry button
Create a page that fetches users and shows a custom error message if the request fails. Use a Client Component with a retry button only for the error state. Keep the initial fetch in a Server Component.
Show solution
// app/users/page.tsx
import { Suspense } from "react";
type User = { id: number; name: string };
async function UserList() {
const response = await fetch("https://jsonplaceholder.typicode.com/users");
if (!response.ok) {
throw new Error("Could not load users");
}
const users: User[] = await response.json();
return (
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
export default function UsersPage() {
return (
<main>
<h1>Users</h1>
<Suspense fallback={<p>Loading users...</p>}>
<UserList />
</Suspense>
</main>
);
}
// app/users/error.tsx
"use client";
export default function UsersError({
error,
reset,
}: {
error: Error & { digest?: string };
reset: () => void;
}) {
return (
<div>
<p>{error.message}</p>
<button onClick={() => reset()}>Try again</button>
</div>
);
}
The Server Component throws on failure, and error.tsx provides a reset button. The retry button is a Client Component, but the data fetching stays on the server.
Written by Shaikh Abdul Shahid
A Full-Stack Developer with experience in PHP, Laravel, JavaScript, and React.
Founder of Online Learner, sharing practical knowledge and programming tutorials.
Building and maintaining real-world web applications since 2017.
Your Feedback
Help us improve by sharing your thoughts.
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
