Server-Side Rendering (SSR)
Server-Side Rendering is a technique where your React components are rendered on the server before being sent to the client. Instead of the browser doing all the work, the server generates the HTML and sends it ready to display.
Think of it like a restaurant: instead of giving you raw ingredients (JavaScript) and expecting you to cook, the server prepares the full meal (HTML) and serves it ready to eat.
How SSR Works
When a user requests a page with SSR, here's what happens:
First, the server receives the request. It then executes your React components, fetches any necessary data, and generates the complete HTML for the page.
This HTML is sent to the browser, which can immediately display it. Meanwhile, JavaScript loads in the background to make the page interactive.
The user sees content faster because they're not waiting for JavaScript to download and execute before seeing anything.
Implementing SSR in Next.js
In Next.js, you implement SSR using the getServerSideProps function. This function runs on every request and fetches the data your page needs.
// app/blog/page.js
export async function getServerSideProps() {
const res = await fetch('https://api.example.com/posts');
const posts = await res.json();
return {
props: {
posts,
},
};
}
export default function Blog({ posts }) {
return (
<div>
<h1>Blog Posts</h1>
{posts.map(post => (
<article key={post.id}>
<h2>{post.title}</h2>
<p>{post.excerpt}</p>
</article>
))}
</div>
);
}
The data fetched in getServerSideProps is passed as props to your component, just like regular React props.
When to Use SSR
SSR is perfect for pages that need fresh data on every request. User-specific dashboards, real-time information, and personalized content are great use cases.
It's also excellent for SEO because search engines can crawl the fully rendered HTML. Pages with dynamic content that changes frequently benefit from SSR.
However, SSR has a downside: it increases server load and can be slower than static generation. For pages that don't change often, consider static generation instead.
SSR vs CSR
Server-Side Rendering differs from Client-Side Rendering in important ways:
With CSR, the browser downloads JavaScript and renders the page. This can be slow on initial load but fast for subsequent navigation.
With SSR, the server renders the page and sends complete HTML. Initial load is fast, but the server does more work.
Next.js lets you choose the best approach for each page. You might use SSR for your blog's homepage and CSR for interactive features.