Data Fetching Basics

πŸ“˜ Next.js πŸ‘ 31 views πŸ“… Dec 22, 2025
⏱ Estimated reading time: 2 min

Data fetching is a core feature of Next.js that allows you to load data from APIs, databases, or external services efficiently. Next.js provides different data-fetching methods depending on where and how the data is needed.


1. Data Fetching in the App Router

In the App Router (app/ directory), data fetching is handled primarily using the fetch() API.
By default, data is fetched on the server, making applications faster and SEO-friendly.


2. Server-Side Data Fetching

Basic Example

async function getData() { const res = await fetch('https://api.example.com/posts'); return res.json(); } export default async function Page() { const data = await getData(); return ( <ul> {data.map(post => ( <li key={post.id}>{post.title}</li> ))} </ul> ); }
  • Runs on the server

  • Data is not exposed to the browser

  • Ideal for SEO and secure data


3. Static Data Fetching (SSG)

By default, fetch() uses static rendering.

await fetch('https://api.example.com/posts');
  • Data is fetched at build time

  • Best for blogs, landing pages, and static content

  • Very fast performance


4. Dynamic Data Fetching

To fetch fresh data on every request, use:

await fetch('https://api.example.com/posts', { cache: 'no-store', });
  • Data is fetched on each request

  • Suitable for dashboards and real-time data


5. Revalidation (ISR)

You can revalidate data after a specific time.

await fetch('https://api.example.com/posts', { next: { revalidate: 60 }, });
  • Data refreshes every 60 seconds

  • Combines speed and freshness


6. Client-Side Data Fetching

For interactive or user-driven data, fetch data on the client.

'use client'; import { useEffect, useState } from 'react'; export default function ClientData() { const [data, setData] = useState([]); useEffect(() => { fetch('/api/posts') .then(res => res.json()) .then(setData); }, []); return <div>{data.length} Posts</div>; }

7. When to Use Which Method

Use CaseMethod
SEO contentServer-side fetch
Static pagesBuild-time fetch
Real-time dataDynamic fetch
User interactionClient-side fetch

Conclusion

Next.js data fetching is flexible and optimized by default. By choosing the right fetching strategyβ€”static, dynamic, or client-sideβ€”you can build fast, scalable, and SEO-friendly applications.


πŸ”’ Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes