Skip to content
intermediatePhase 38 · Web Performance

Server-Side Rendering

Implement SSR for improved initial load time and SEO.

45m
0 problems
Topic Progress0%

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

  1. Faster First Contentful Paint: HTML renders immediately
  2. Better Largest Contentful Paint: Content visible sooner
  3. Improved Time to Interactive: Progressive hydration

SEO Benefits

  1. Full HTML content: Search engines can crawl
  2. Meta tags: Rendered on server
  3. Structured data: Available for crawlers

User Experience

  1. No blank screen: Content visible immediately
  2. Works without JavaScript: Basic content available
  3. 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

  1. Server load: Each request requires server computation
  2. TTFB: Server processing adds latency
  3. Memory leaks: Server-side state management
  4. Deployment complexity: Need Node.js server
  5. Hydration mismatch: Server and client render differently

Solutions

  1. Edge rendering: Run SSR at edge locations
  2. ISR: Cache and revalidate SSR pages
  3. Streaming SSR: Send HTML progressively
  4. Partial hydration: Only hydrate interactive parts

Practice Problems

0/3solved
Build Server-Side Rendering Component

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 needed
Server-Side Rendering Testing

Write 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 tests
Server-Side Rendering Performance

Optimize 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 analysis

Quiz

1. What is the main benefit of SSR for SEO?

Question 1 options

2. What is hydration?

Question 2 options

3. What is the primary purpose of Server-Side Rendering?

Question 3 options

4. What is a common mistake when implementing Server-Side Rendering?

Question 4 options

Flashcards

Question

What is SSR?

Answer

Server-Side Rendering - server generates HTML that browser hydrates with JavaScript.

Question

What are the benefits of SSR?

Answer

Faster FCP, better SEO, works without JavaScript, better UX on slow devices.

Question

What is hydration?

Answer

JavaScript attaching event handlers to server-rendered HTML to make it interactive.

Question

What frameworks support SSR?

Answer

Next.js (React), Nuxt.js (Vue), Remix, SvelteKit, Astro.

Question

What is Server-Side Rendering?

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

  1. Server renders React to HTML
  2. HTML sent to browser
  3. Browser displays HTML
  4. JavaScript hydrates
  5. 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