Blog>
Snippets

Using getServerSideProps for Server-Side Rendering

Showcase how to use Next.js' getServerSideProps function to fetch data server-side for pre-rendering pages with dynamic data.
export async function getServerSideProps(context) {
  // Fetch data from an external API endpoint
  const res = await fetch(`https://api.example.com/data`);
  const data = await res.json();

  // The returned object will be passed as props to the page component
  return { props: { data } };
}
This JavaScript function is part of a Next.js page. It uses the getServerSideProps function to fetch data from an external API server-side. The fetched data is then serialized into JSON and passed as props to the page component when it is rendered. This is done for each request, enabling server-side rendering of dynamic content.
import React from 'react';

function Page({ data }) {
  // Render the page with data received as props from getServerSideProps
  return (
    <div>
      <h1>Data Fetched Server-Side</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
}

export default Page;
This is the React page component that corresponds to the getServerSideProps function above. The 'data' prop received from getServerSideProps is used here to render the page. The data is displayed in a preformatted text block, allowing users to see the data fetched from the server-side.
body {
  font-family: Arial, sans-serif;
}
h1 {
  color: #333;
}
pre {
  background-color: #f7f7f7;
  border: 1px solid #eee;
  padding: 20px;
}
This CSS provides basic styling for the page. It sets a font family for the body element and colors and styles the h1 element and the pre (preformatted text) element for displaying the fetched data more clearly and with a distinguishable background color.