Fetching data in Next.js allows you to retrieve information from APIs or external services using the built-in fetch() API. It can be done in both Server Components and Client Components (App Router).
- Fetch data using the built-in fetch() API.
- Supports external APIs and internal Route Handlers.
- Works in both Server and Client Components.
- Supports caching and revalidation options.
Implementing External API Data Fetching in Next.js
Follow the steps below:
Step 1: Create a New Next.js Project
npx create-next-app@latest api-fetch-appStep 2: Navigate to the Project Directory
cd api-fetch-appStep 3: Project Structure
api-fetch-app/
│
├── app/
│ ├── posts/
│ │ └── page.js
│ └── page.js
├── package.json
└── ...
Step 4: Fetching Posts from an External API
Create the following file:
app/posts/page.jsexport default async function Posts() {
const res = await fetch(
"https://jsonplaceholder.typicode.com/posts"
);
const posts = await res.json();
return (
<main
style={{
minHeight: "100vh",
background: "#f6f8fc",
padding: "40px",
fontFamily: "Arial, sans-serif",
}}
>
<div
style={{
maxWidth: "900px",
}}
>
<h1
style={{
fontSize: "42px",
marginBottom: "10px",
color: "#222",
}}
>
Latest Posts
</h1>
<p
style={{
color: "#666",
marginBottom: "40px",
}}
>
Here are the latest posts fetched from JSONPlaceholder API.
</p>
{posts.slice(0, 10).map((post, index) => (
<div
key={post.id}
style={{
display: "flex",
alignItems: "center",
justifyContent: "space-between",
background: "#fff",
padding: "18px 24px",
marginBottom: "16px",
borderRadius: "12px",
boxShadow: "0 4px 12px rgba(0,0,0,0.08)",
}}
>
<div
style={{
display: "flex",
alignItems: "center",
gap: "20px",
}}
>
<div
style={{
width: "45px",
height: "45px",
borderRadius: "10px",
background: "#ede9fe",
color: "#6d28d9",
display: "flex",
justifyContent: "center",
alignItems: "center",
fontWeight: "bold",
fontSize: "18px",
}}
>
{index + 1}
</div>
<span
style={{
fontSize: "18px",
fontWeight: "600",
color: "#222",
}}
>
{post.title}
</span>
</div>
<span
style={{
background: "#ede9fe",
color: "#6d28d9",
padding: "8px 14px",
borderRadius: "20px",
fontWeight: "bold",
}}
>
Post #{index + 1}
</span>
</div>
))}
</div>
</main>
);
}
Step 5: Run the Application
Start the development server:
npm run devOpen the following URL in your browser:
http://localhost:3000/postsOutput:


