What is getServerSideProps in Next.js: Server-Side Data Fetching Explained
getServerSideProps is a special function in Next.js that runs on the server before a page is rendered. It fetches data on each request and passes it as props to the page, enabling server-side rendering with fresh data every time.How It Works
Imagine you want to show a page that always has the latest information, like news or user data. getServerSideProps runs on the server every time someone visits that page. It fetches the needed data first, then sends the fully prepared page to the user's browser.
This is like a chef preparing a fresh meal for each customer instead of serving leftovers. Because the data is fetched on the server, the user sees the updated content immediately when the page loads, improving experience and SEO.
Example
This example shows a Next.js page that fetches a random joke from an API every time it loads using getServerSideProps.
import React from 'react'; export async function getServerSideProps() { const res = await fetch('https://official-joke-api.appspot.com/random_joke'); const joke = await res.json(); return { props: { joke }, }; } export default function JokePage({ joke }) { return ( <main> <h1>Random Joke</h1> <p><strong>{joke.setup}</strong></p> <p>{joke.punchline}</p> </main> ); }
When to Use
Use getServerSideProps when you need fresh data on every page request. This is important for pages that change often or depend on user-specific data, like dashboards, live feeds, or personalized content.
It is not ideal for static content because it runs on every request, which can slow down your site if overused. For static or rarely changing data, consider getStaticProps instead.
Key Points
- Runs on server: Executes on each request before rendering.
- Fetches fresh data: Ensures the page shows up-to-date information.
- Improves SEO: Content is ready on page load for search engines.
- Slower than static: Can add delay since it runs every time.
- Returns props: Passes data to the page component as props.
Key Takeaways
getServerSideProps fetches data on the server for every page request.