Uncover the power of Server-Side Rendering (SSR) in Next.js. Learn how SSR works, when to use it, and see practical code examples for real projects.
Table of content
Next.js is a leading React framework that makes building powerful web applications seamless. One of its standout features is Server-Side Rendering (SSR). But what exactly is SSR, and why should you care as a web developer? This article demystifies SSR in Next.js by explaining its benefits, use cases, and offering practical code examples to get you started.
Server-Side Rendering (SSR) is the process where your page’s content is rendered on the server, not in the browser. When a user requests a page, the server generates the HTML and sends it to the client—making your site faster and more SEO-friendly right from the start.
Next.js gives you SSR by simply exporting an async getServerSideProps
function from your page. This function runs on the server with every request.
// pages/news.js
export async function getServerSideProps(context) {
const res = await fetch('https://api.example.com/news');
const news = await res.json();
return {
props: { news },
};
}
export default function News({ news }) {
return (
<div>
<h1>Latest News</h1>
<ul>
{news.map(article => (
<li key={article.id}>{article.title}</li>
))}
</ul>
</div>
);
}
Every time someone visits /news
, the data is fetched server-side just before rendering the page.
// pages/profile.js
export async function getServerSideProps(context) {
const token = context.req.cookies.token;
if (!token) {
return { redirect: { destination: '/login', permanent: false } };
}
// Fetch user with token
const res = await fetch('https://api.example.com/me', {
headers: { Authorization: `Bearer ${token}` },
});
const user = await res.json();
return { props: { user } };
}
export default function Profile({ user }) {
return <div>Welcome, {user.name}!</div>;
}
SSR in Next.js brings performance, SEO, and flexibility to your web projects. By simply leveraging getServerSideProps
, you unlock server power with minimal code change. Consider your project’s needs, and blend SSR with SSG and CSR where it makes the most sense. Happy coding!