Blog>
Snippets

SSR with Dynamic Routes

Explain how to fetch data for dynamic routes in getServerSideProps based on query parameters or page slugs.
import { GetServerSideProps } from 'next';

export const getServerSideProps: GetServerSideProps = async (context) => {
  // Extract the dynamic part of the URL (e.g., slug or id) from the `context` object
  const { params } = context;
  let data = {};

  // Fetch data based on the slug or id, assuming an id is the dynamic route
  if (params?.id) {
    const res = await fetch(`https://api.example.com/data/${params.id}`);
    data = await res.json();
  }

  // Return the fetched data as props
  return {
    props: { data },
  };
};

// Sample React component using the data from getServerSideProps
const DynamicPage = ({ data }) => {
  // Render the page using the fetched data
  return (
    <div>
      <h1>{data.title}</h1>
      <p>{data.content}</p>
    </div>
  );
};

export default DynamicPage;
This code snippet is using Next.js server-side rendering (SSR) with dynamic routes. The getServerSideProps function is an async function that gets executed on every page request. Inside this function, the dynamic part of the URL is obtained from the context object's params. It fetches data from an API based on this dynamic parameter (like an id or slug) and then this data is passed as props to the component, which can use it to render the page on the server before sending it to the client.