Blog>
Snippets

Basic getServerSideProps Usage

Demonstrate fetching data server-side on each request with Next.js using getServerSideProps for server-rendered pages.
export async function getServerSideProps(context) {
  // Fetch data from an external API
  const res = await fetch(`https://api.example.com/data`);
  const data = await res.json();

  // Pass data to the page via props
  return { props: { data } };
}
This function is called getServerSideProps, it's an async function which is used in Next.js to fetch data on the server-side before rendering the page. It fetches data from an external API, converts the response to JSON, and then returns an object with a props key containing the fetched data. This data is then accessible in the page's component via its props.
export default function Page({ data }) {
  // Render data on the page
  return (
    <div>
      <h1>My Data</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
}
This is the React component that consumes the props provided by getServerSideProps. It destructures the data prop and renders it on the page, displaying the data inside a preformatted text block.