Server-Side Rendering (SSR) is a technique where the server generates HTML for each request and sends it to the client. This approach offers several advantages, including improved performance, SEO benefits, and better user experience. In this section of the Next.js course, we will explore how to implement SSR using Next.js, focusing on data fetching strategies.
Server-Side Rendering (SSR) is a method where the server generates HTML for each request and sends it to the client. Unlike Client-Side Rendering (CSR), which renders pages in the browser, SSR pre-renders pages on the server before sending them to the client. This results in faster initial page loads and better SEO performance because search engines can crawl and index the rendered HTML.
Next.js provides built-in support for Server-Side Rendering out of the box. To enable SSR, you need to create a new Next.js project or modify an existing one.
To create a new Next.js project, run the following command:
npx create-next-app@latest my-nextjs-app
cd my-nextjs-app
This will set up a basic Next.js application with all necessary configurations for SSR.
Next.js uses two special functions to enable SSR: getServerSideProps and getStaticProps. In this section, we will focus on getServerSideProps, which is specifically designed for SSR.
The getServerSideProps function allows you to fetch data on each request. This means that the server generates a new HTML page for each request based on the latest data.
Here's an example of how to use getServerSideProps:
// pages/index.js
export async function getServerSideProps() {
// Fetch data from an 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 } };
}
export default function Home({ data }) {
return (
<div>
<h1>Server-Side Rendered Page</h1>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
}
In this example:
getServerSideProps function fetches data from an external API.Home component as props./ route will trigger a new server-side render with the latest data.revalidate to avoid unnecessary requests.Here's an example with error handling and revalidation:
// pages/index.js
export async function getServerSideProps() {
try {
const res = await fetch('https://api.example.com/data');
if (!res.ok) {
throw new Error('Failed to fetch data');
}
const data = await res.json();
return { props: { data }, revalidate: 10 }; // Revalidate every 10 seconds
} catch (error) {
console.error(error);
return { props: { error: 'Failed to load data' } };
}
}
export default function Home({ data, error }) {
if (error) {
return <div>{error}</div>;
}
return (
<div>
<h1>Server-Side Rendered Page</h1>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
}
Next.js also supports Static Site Generation (SSG) using getStaticProps. The main difference between SSR and SSG is when the HTML is generated:
Choosing between SSR and SSG depends on your specific use case. If you need real-time data or frequent updates, SSR is more appropriate. For static content that doesn't change often, SSG is a better choice.
Server-Side Rendering (SSR) in Next.js provides a powerful way to improve the performance and SEO of your application. By using getServerSideProps, you can fetch data on each request and generate dynamic HTML pages. This approach is particularly useful for applications that require real-time data or frequent updates.
In this section, we explored how to implement SSR in Next.js, including best practices for error handling and caching. Understanding these concepts will help you build more efficient and user-friendly web applications.
Feel free to experiment with different data fetching strategies and configurations to optimize your Next.js application for SSR.