Go Back

Apr 17, 2025

Data Fetching and Dynamic Routing

These features empower you to build powerful, SEO-friendly applications that can serve both static and dynamic data.

Data Fetching and Dynamic Routing

1. Data Fetching Strategies

Next.js offers several methods to fetch data, each suited for different use cases:

a. Static Site Generation (SSG)

// pages/posts/index.js
export async function getStaticProps() {
  const res = await fetch('https://api.example.com/posts');
  const posts = await res.json();
  return { props: { posts } };
}

export default function PostsPage({ posts }) {
  return (
    <ul>
      {posts.map(post => (
        <li key={post.id}>{post.title}</li>
      ))}
    </ul>
  );
}

b. Dynamic Paths with getStaticPaths

// pages/posts/[id].js
export async function getStaticPaths() {
  const res = await fetch('https://api.example.com/posts');
  const posts = await res.json();
  const paths = posts.map(post => ({ params: { id: post.id.toString() } }));
  return { paths, fallback: 'blocking' };
}

export async function getStaticProps({ params }) {
  const res = await fetch(`https://api.example.com/posts/${params.id}`);
  const post = await res.json();
  return { props: { post } };
}

c. Server-Side Rendering (SSR)

export async function getServerSideProps(context) {
  const res = await fetch('https://api.example.com/user', { headers: { cookie: context.req.headers.cookie } });
  const user = await res.json();
  return { props: { user } };
}

d. Incremental Static Regeneration (ISR)

export async function getStaticProps() {
  const data = await fetchData();
  return {
    props: { data },
    revalidate: 60, // regenerate at most once every 60 seconds
  };
}

e. Client-Side Data Fetching

import useSWR from 'swr';

function Profile() {
  const { data, error } = useSWR('/api/user', fetcher);
  if (error) return <div>Failed to load</div>;
  if (!data) return <div>Loading...</div>;
  return <div>Welcome, {data.name}!</div>;
}

2. Advanced Dynamic Routing

File-based routing in Next.js allows powerful patterns out of the box:

a. Basic Dynamic Routes

b. Catch-All Routes

c. Optional Catch-All Routes

d. Nested Routes

3. Preview Mode

Enable Preview Mode to toggle between draft and published content in SSG pages:

// pages/api/preview.js
export default function handler(req, res) {
  res.setPreviewData({});
  res.redirect(req.query.redirect || '/');
}

In your page:

export async function getStaticProps({ preview }) {
  const data = await fetchPosts({ draft: preview });
  return { props: { data } };
}

With these techniques, you can fetch and render data in Next.js with flexibility and performance, tailoring each page to your application’s needs. In the next chapter, we’ll dive into styling and theming strategies in Next.js.