How SSR Works
How SSR Works
Server renders React components to HTML.
SSR Process
1. Request → Server
2. Server executes React components
3. Server generates HTML string
4. HTML sent to browser
5. Browser displays HTML immediately
6. JavaScript loads and hydrates
7. App becomes interactive
Basic SSR Setup
// server.js
import express from 'express';
import React from 'react';
import { renderToString } from 'react-dom/server';
import App from './App';
const app = express();
app.get('*', (req, res) => {
const html = renderToString(<App url={req.url} />);
res.send(`
<!DOCTYPE html>
<html>
<head>
<title>SSR App</title>
</head>
<body>
<div id="root">${html}</div>
<script src="/client.js"></script>
</body>
</html>
`);
});
app.listen(3000);
Next.js SSR
// pages/products/[id].js
export async function getServerSideProps({ params }) {
const product = await fetchProduct(params.id);
if (!product) {
return { notFound: true };
}
return {
props: { product },
};
}
export default function ProductPage({ product }) {
return (
<div>
<h1>{product.name}</h1>
<p>{product.description}</p>
<p>${product.price}</p>
</div>
);
}
Data Fetching in SSR
// Parallel data fetching
export async function getServerSideProps() {
const [products, categories] = await Promise.all([
fetchProducts(),
fetchCategories(),
]);
return {
props: { products, categories },
};
}
// Conditional fetching
export async function getServerSideProps(context) {
const session = await getSession(context);
if (!session) {
return { redirect: { destination: '/login' } };
}
const userData = await fetchUserData(session.id);
return { props: { userData } };
}
SSR Benefits
SSR Benefits
Performance Benefits
- Faster First Contentful Paint: HTML renders immediately
- Better Largest Contentful Paint: Content visible sooner
- Improved Time to Interactive: Progressive hydration
SEO Benefits
- Full HTML content: Search engines can crawl
- Meta tags: Rendered on server
- Structured data: Available for crawlers
User Experience
- No blank screen: Content visible immediately
- Works without JavaScript: Basic content available
- Better on slow devices: Server does heavy lifting
SSR Performance Metrics
// Monitor SSR performance
export async function getServerSideProps() {
const start = performance.now();
const data = await fetchData();
const duration = performance.now() - start;
console.log(`SSR took ${duration}ms`);
return { props: { data, ssrDuration: duration } };
}
SSR Caching
// Edge caching for SSR
// Next.js ISR
export async function getServerSideProps() {
return {
props: { data: await fetchData() },
// This is ISR, not SSR
// revalidate: 60,
};
}
// Redis caching
import Redis from 'ioredis';
const redis = new Redis();
export async function getServerSideProps() {
const cacheKey = 'products';
let data = await redis.get(cacheKey);
if (!data) {
data = await fetchProducts();
await redis.set(cacheKey, JSON.stringify(data), 'EX', 3600);
} else {
data = JSON.parse(data);
}
return { props: { data } };
}
SSR Frameworks
SSR Frameworks
Next.js
// pages/index.js
export async function getServerSideProps() {
const posts = await fetchPosts();
return { props: { posts } };
}
export default function Home({ posts }) {
return (
<div>
<h1>Blog</h1>
{posts.map(post => (
<article key={post.id}>
<h2>{post.title}</h2>
<p>{post.excerpt}</p>
</article>
))}
</div>
);
}
Remix
// app/routes/posts.jsx
import { json } from '@remix-run/node';
import { useLoaderData } from '@remix-run/react';
export async function loader() {
const posts = await fetchPosts();
return json({ posts });
}
export default function Posts() {
const { posts } = useLoaderData();
return (
<div>
{posts.map(post => (
<Link key={post.id} to={`/posts/${post.id}`}>
{post.title}
</Link>
))}
</div>
);
}
Nuxt.js (Vue)
<!-- pages/products.vue -->
<script setup>
const { data: products } = await useFetch('/api/products');
</script>
<template>
<div>
<h1>Products</h1>
<ProductList :products="products" />
</div>
</template>
SSR Challenges
- Server load: Each request requires server computation
- TTFB: Server processing adds latency
- Memory leaks: Server-side state management
- Deployment complexity: Need Node.js server
- Hydration mismatch: Server and client render differently
Solutions
- Edge rendering: Run SSR at edge locations
- ISR: Cache and revalidate SSR pages
- Streaming SSR: Send HTML progressively
- Partial hydration: Only hydrate interactive parts
Practice Problems
Create a reusable React component implementing Server-Side Rendering. Include proper state management and accessibility.
Solution
// Production-ready component with:
// - Proper TypeScript types
// - Accessibility (ARIA)
// - Error boundaries
// - Loading states
// - Memoization where neededWrite unit and integration tests for Server-Side Rendering using React Testing Library.
Solution
// Test coverage:
// 1. Rendering tests
// 2. Interaction tests
// 3. Edge case tests
// 4. Accessibility testsOptimize Server-Side Rendering for performance. Consider memoization, code splitting, and bundle size.
Solution
// Optimization techniques:
// 1. React.memo / useMemo / useCallback
// 2. Code splitting with lazy()
// 3. Virtual scrolling for lists
// 4. Image lazy loading
// 5. Bundle analysisQuiz
1. What is the main benefit of SSR for SEO?
2. What is hydration?
3. What is the primary purpose of Server-Side Rendering?
4. What is a common mistake when implementing Server-Side Rendering?
Flashcards
Question
What is SSR?
Click to reveal answer
Answer
Server-Side Rendering - server generates HTML that browser hydrates with JavaScript.
Question
What are the benefits of SSR?
Click to reveal answer
Answer
Faster FCP, better SEO, works without JavaScript, better UX on slow devices.
Question
What is hydration?
Click to reveal answer
Answer
JavaScript attaching event handlers to server-rendered HTML to make it interactive.
Question
What frameworks support SSR?
Click to reveal answer
Answer
Next.js (React), Nuxt.js (Vue), Remix, SvelteKit, Astro.
Question
What is Server-Side Rendering?
Click to reveal answer
Answer
Server-Side Rendering is a key concept in frontend development.
Revision Notes
Key Takeaways
- 1.SSR renders HTML on the server for faster initial load
- 2.Hydration makes server-rendered HTML interactive
- 3.SSR provides better SEO with full HTML content
- 4.Next.js, Remix, and Nuxt.js support SSR
- 5.Challenges include server load and hydration mismatch
Interview Tips
- •Explain the SSR process and hydration
- •Discuss SSR benefits for SEO and performance
- •Know how to implement SSR with Next.js
Cheat Sheet
SSR Cheat Sheet
How SSR Works
- Server renders React to HTML
- HTML sent to browser
- Browser displays HTML
- JavaScript hydrates
- App becomes interactive
Benefits
- Faster FCP
- Better SEO
- Works without JS
Challenges
- Server load
- TTFB latency
- Hydration mismatch
Frameworks
- Next.js (React)
- Nuxt.js (Vue)
- Remix