Blog>
Snippets

Dynamic Nested Routes with Server-Side Data Fetching

Demonstrate how to implement nested routing with dynamic paths using getServerSideProps for data fetching and populating page components.
import { useRouter } from 'next/router';
import { useEffect, useState } from 'react';

const Post = ({ postData }) => {
  // Component to render post data
  return (
    <div>
      <h1>{postData.title}</h1>
      <p>{postData.content}</p>
    </div>
  );
};

export async function getServerSideProps(context) {
  const { params } = context;
  // Fetching server-side data based on dynamic route parameter
  const res = await fetch(`https://example.com/posts/${params.id}`);
  const postData = await res.json();

  // Returns an object with the fetched data as 'props'
  return {
    props: {
      postData,
    },
  };
}

export default Post;
This code defines a Next.js page component that renders a post. The dynamic part of the route (the post ID) is fetched using getServerSideProps, which retrieves post data from a server before the page is rendered. The postData is passed as a prop to the Post component.
import { useRouter } from 'next/router';
import Link from 'next/link';

const PostList = ({ posts }) => {
  return (
    <ul>
      {posts.map((post) => (
        <li key={post.id}>
          // Link to a dynamic route
          <Link href={`/posts/${post.id}`}>{post.title}</Link>
        </li>
      ))}
    </ul>
  );
};

export default PostList;
This code provides a component that renders a list of posts with links. Each link directs to a dynamic route based on the post's ID.
export async function getServerSideProps() {
  // Fetches list of posts for server-side rendering
  const res = await fetch('https://example.com/posts');
  const posts = await res.json();

  // Returns the list of posts as props to the page component
  return {
    props: {
      posts,
    },
  };
}
This is the getServerSideProps function for the page that lists all posts. It fetches the posts data from a server before rendering the page server-side. The data is then made available as a prop to the PostList component.