Data Fetching Methods in Next.js

Next.js supports multiple data fetching strategies to balance performance and dynamic content needs, including getServerSideProps, getStaticProps, and getInitialProps.

🧠 getServerSideProps

  • SSR (Server-Side Rendering): Fetches data on each request, ensuring real-time freshness.
  • Use Case: Ideal for pages where the content changes frequently or needs to be always up to date.

Example:

javascript
1export async function getServerSideProps() { 2 const res = await fetch('https://api.example.com/data'); 3 const data = await res.json(); 4 return { props: { data } }; 5}

🧠 getStaticProps

  • SSG (Static Site Generation): Fetches data at build time, generating static HTML.
  • Use Case: Best for pages with data that doesn't change often (e.g., blog posts, documentation).

Example:

javascript
1export async function getStaticProps() { 2 const res = await fetch('https://api.example.com/data'); 3 const data = await res.json(); 4 return { props: { data } }; 5}

🧠 getInitialProps

  • Universal: Runs on the server during SSR and on the client during client-side navigation.
  • Note: Generally used for backward compatibility; not recommended for new projects.

In short:

  • getServerSideProps: Server-side rendering, fetch on every request.
  • getStaticProps: Static generation, fetch at build time.
  • getInitialProps: Legacy method for both SSR and client use, less preferred today.