Blog>
Snippets

Fetching Data for Dynamic Pages using getServerSideProps

Demonstrate how to fetch data based on the dynamic route parameter using Next.js's getServerSideProps function for server-side rendering.
import { useRouter } from 'next/router';
import { useEffect, useState } from 'react';

export async function getServerSideProps(context) {
  // Extract the dynamic part of the URL (e.g., id)
  const { params } = context;
  const { id } = params;

  // Fetch the required data using the dynamic id
  const res = await fetch(`https://api.example.com/data/${id}`);
  const data = await res.json();

  // Pass the fetched data to the page via props
  return {
    props: { data }
  };
}

// The page component that uses the fetched data
function DynamicPage({ data }) {
  const router = useRouter();

  // Render the data on the page
  return (
    <div>
      <h1>Dynamic Page Content</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
}

export default DynamicPage;
This piece of code demonstrates how to use Next.js's getServerSideProps function to fetch data from an API based on a dynamic route parameter before rendering the page on the server. The getServerSideProps function extracts the dynamic route parameter (e.g., 'id') from the context and then uses it to fetch the relevant data. The fetched data is then passed to the page component via props, which renders it.