Server-Side Rendering (SSR)
Learn how to pre-render React applications on the server for better performance and SEO.
1. What is Server-Side Rendering?
Server-Side Rendering (SSR) is a technique where React components are rendered to HTML on the server and sent to the client. This ensures that the client receives a fully-rendered page, improving performance and SEO.
import ReactDOMServer from 'react-dom/server';
Key Features:
- SEO-Friendly: Content is pre-rendered and crawlable by search engines.
- Performance Optimization: Faster page load times as HTML is delivered immediately.
2. Setting Up SSR
To set up SSR with React, you can use frameworks like Next.js or manually configure SSR with Node.js:
// Example with Node.js and Express import express from 'express'; import React from 'react'; import ReactDOMServer from 'react-dom/server'; import App from './App'; const app = express(); app.get('*', (req, res) => { const html = ReactDOMServer.renderToString(); res.send(` SSR Example ${html}`); }); app.listen(3000, () => { console.log('Server is running on http://localhost:3000'); });
Explanation: The server renders the React application to a string and embeds it into an HTML template.
3. Benefits of SSR
- Better SEO: Pre-rendered content improves search engine rankings.
- Faster Initial Load: Users see the page content immediately without waiting for JavaScript to load.
4. SSR vs Client-Side Rendering
Comparison between SSR and traditional client-side rendering:
- SSR: Pre-renders content on the server, suitable for SEO-sensitive applications.
- Client-Side Rendering: Renders content on the client, suitable for dynamic, user-driven applications.
5. Frameworks Supporting SSR
- Next.js: A React framework with built-in SSR and static site generation capabilities.
- Gatsby: A static site generator with SSR features.
6. Example: SSR with Next.js
// pages/index.js export async function getServerSideProps() { return { props: { message: "Hello from SSR!" }, }; } export default function Home({ message }) { return{message}
; }
Explanation: The getServerSideProps
function fetches data at request time, and the page is pre-rendered on the server.