Server Side Rendering in NextJS
🚀 Server-Side Rendering (SSR) in Next.js
Server-Side Rendering (SSR) in Next.js allows you to fetch data and render pages dynamically on every request. This is useful for SEO, personalization, and frequently updated data.
📌 1. Why Use SSR?
✔️ SEO-friendly: Content is fully rendered before reaching the client
✔️ Dynamic content: Fetch fresh data on every request
✔️ No stale data: Always fetches up-to-date information
📌 2. How SSR Works in Next.js
Uses
getServerSideProps()to fetch data at request timeThe page is rendered on the server and sent to the client
The HTML is fully generated before reaching the browser
📌 3. Implementing SSR with getServerSideProps()
<div> export async function getServerSideProps(context) { const { id } = context.query; // Get dynamic parameter const res = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`); <div> <h1>{post.title}</h1> <p>{post.body}</p> </div> );}
✅ Visiting /post/3 will fetch and render post 3 dynamically
📌 6. Redirects in SSR
You can redirect users dynamically using SSR.
🔹 Example: Redirect if No Data Found
export async function getServerSideProps(context) { const res = await fetch("https://jsonplaceholder.typicode.com/posts/999"); if (!res.ok) { return { redirect: { destination: "/not-found", permanent: false, }, }; } const data = await res.json(); return { props: { post: data } };}
✅ Redirects users if the requested data is missing
📌 7. Handling API Errors in SSR
You can return a custom 404 error if the API request fails.
export async function getServerSideProps() { try { const res = await fetch("https://jsonplaceholder.typicode.com/posts/999"); if (!res.ok) { return { notFound: true }; } const data = await res.json(); return { props: { post: data } }; } catch (error) { return { props: { error: "Failed to fetch data" } }; }}
✅ Automatically shows a 404 page if data is unavailable
📌 8. SSR vs. Static Generation vs. Client-Side Rendering
| Feature | SSR (getServerSideProps) | Static (getStaticProps) | CSR (useEffect) |
|---|---|---|---|
| When is data fetched? | On every request | At build time | In the browser |
| SEO-friendly? | ✅ Yes | ✅ Yes | ❌ No |
| Suitable for? | Dynamic content | Static content | Interactive UI |
📌 9. Summary: Best Practices for SSR
✅ Use SSR for pages requiring fresh data
✅ Avoid SSR for static pages (use getStaticProps instead)
✅ Handle errors properly (use notFound or redirect)