Blog>
Snippets

Basic Data Fetching with getServerSideProps

Demonstrate how to use Next.js `getServerSideProps` for server-side rendering and fetching data on each request, useful for highly dynamic content.
import { GetServerSideProps } from 'next';

export const getServerSideProps: GetServerSideProps = async (context) => {
  // Fetch data from 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 } };
};

const Page = ({ data }) => {
  // Render data on the page
  return (
    <div>
      <h1>Data from Server</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
};

export default Page;
This code shows the usage of Next.js getServerSideProps function to fetch data from an external API on each request and pass it to the page component's props. The fetched data is then rendered inside the page component. The GetServerSideProps type is imported from Next.js for TypeScript support.