Server-Side Rendering (SSR) is a powerful rendering strategy in Next.js that allows you to fetch data on the server before sending the fully rendered HTML to the client. This means that when a user requests a page, the server has already done the work of gathering all necessary data and constructing the HTML. This approach offers several key benefits, including improved SEO, faster perceived performance for initial page loads, and a better user experience, especially on slower networks or devices.
The core of SSR in Next.js revolves around the getServerSideProps function. This function is exported from a page file and is executed on the server for every request. This is in contrast to static generation methods like getStaticProps, which run at build time. When getServerSideProps is present, Next.js will render the page on the server, inject the data returned by getServerSideProps into the page's props, and send the HTML to the browser.
export async function getServerSideProps(context) {
// Fetch data from an external API or database
const res = await fetch('https://api.example.com/data');
const data = await res.json();
// Pass data to the page via props
return {
props: {
myData: data,
},
};
}Inside getServerSideProps, you have access to a context object. This object contains useful properties such as params (for dynamic routes), req (the incoming Node.js HTTP request object), res (the outgoing Node.js HTTP response object), and query (the URL query parameters). You can leverage these to fetch data specific to the request, like user authentication details or specific resource IDs.
function MyPage({ myData }) {
// Render your page using the data from props
return (
<div>
<h1>My Data</h1>
<pre>{JSON.stringify(myData, null, 2)}</pre>
</div>
);
}
export default MyPage;The data returned from getServerSideProps is then made available as props to your page component. This allows your component to render the UI using the fetched server-side data. Crucially, the client-side JavaScript will then rehydrate the page, making it interactive without needing to re-fetch the data.