Blog>
Snippets

Fetching Data with getServerSideProps

Create a simple example that uses getServerSideProps to fetch data on the server side and pass it as props to a page component at request time.
import { GetServerSideProps } from 'next';

export const getServerSideProps: GetServerSideProps = async (context) => {
  const res = await fetch(`https://api.example.com/data`);
  const data = await res.json();

  if (!data) {
    return {
      notFound: true,
    };
  }

  return {
    props: { data }, // will be passed to the page component as props
  };
};

const Page = ({ data }) => (
  // Render data
  <div>{JSON.stringify(data)}</div>
);

export default Page;
This snippet shows a Next.js page using getServerSideProps to fetch data from an API on the server side before rendering. The fetched data is then passed to the page's component as a prop.