A key technology underpinning the applications we develop is React as it offers many benefits. Providing great developer tools, and backed by a strong community, it boosts productivity and facilitates the process of writing and maintaining front-end components. Also, as React uses a Virtual DOM, the performance is vastly superior to a traditional JavaScript application.
React is well suited to building large-scale applications with data that repeatedly changes.
React provides a more natural creation of interactive UIs, a component-based structure, and much more. This is beneficial for building the design systems and component libraries that are an important part of rolling out customer experience improvements and achieving digital transformation benefits.
However, it is essential to understand that React renders your application on the client-side, meaning that all JavaScript files and dependencies must be downloaded to the user's browser before the page can start to be rendered by the browser. The fact remains that while React is extremely fast once the application is loaded, there is an increase in the initial load time (over vanilla HTML). Also, only some web crawlers can index the website or application.
Server-side rendering (SSR) aims to address these problems. In this article, I want to introduce you to SSR within React, the reasons to use it, and some popular frameworks for rendering React on the server-side.
Server-side and client-side rendering
Client-side rendering (CSR)
In client-side rendering, the browser receives a minimal HTML document from the server, usually containing just a basic structure and a script tag that references the JavaScript bundle. The JavaScript then runs in the browser, creating the DOM elements and rendering the complete page.
Advantages of CSR:
- Fast subsequent page loads after initial load
- Rich interactive experiences
- Reduced server load
- Works well for complex, dynamic applications
Disadvantages of CSR:
- Slower initial page load
- SEO challenges
- Poor performance on slower devices
- Requires JavaScript to be enabled
Server-side rendering (SSR)
With server-side rendering, the server processes the React components and generates the complete HTML before sending it to the browser. The browser receives a fully rendered page that can be displayed immediately, with JavaScript enhancing the page after it loads.
Advantages of SSR:
- Faster initial page load and first contentful paint
- Better SEO as search engines can crawl the full HTML
- Works without JavaScript enabled
- Improved performance on slower devices and networks
Disadvantages of SSR:
- More complex setup and deployment
- Higher server resource usage
- Potentially slower subsequent navigation
- More complex state management
Key benefits of React SSR
1. Improved SEO
Search engines can more easily crawl and index server-rendered pages because the content is available in the initial HTML response. While modern search engines like Google can execute JavaScript, SSR ensures your content is immediately accessible to all crawlers.
// SSR ensures this content is available immediately
const ProductPage = ({ product }) => (
<div>
<h1>{product.title}</h1>
<p>{product.description}</p>
<meta property="og:title" content={product.title} />
<meta property="og:description" content={product.description} />
</div>
);
2. Better Performance Metrics
SSR significantly improves key performance metrics:
- First Contentful Paint (FCP): Users see content faster
- Largest Contentful Paint (LCP): Main content loads quicker
- Time to Interactive (TTI): Page becomes interactive sooner
- First Meaningful Paint (FMP): Meaningful content appears earlier
3. Improved User Experience
Users see content immediately rather than waiting for JavaScript to load and execute. This is especially important for:
- Users on slower networks
- Mobile devices with limited processing power
- Users in areas with poor connectivity
- First-time visitors who haven't cached your assets
4. Social Media Sharing
When URLs are shared on social media platforms, they can properly extract metadata, images, and descriptions from the server-rendered HTML:
// This meta information is available immediately with SSR
const BlogPost = ({ post }) => (
<>
<Helmet>
<title>{post.title}</title>
<meta property="og:title" content={post.title} />
<meta property="og:description" content={post.excerpt} />
<meta property="og:image" content={post.featuredImage} />
</Helmet>
<article>
<h1>{post.title}</h1>
<div>{post.content}</div>
</article>
</>
);
Popular React SSR Frameworks
Next.js
Next.js is the most popular React framework for SSR, offering both static site generation (SSG) and server-side rendering out of the box.
// pages/product/[id].js
export async function getServerSideProps({ params }) {
const product = await fetchProduct(params.id);
return {
props: {
product,
},
};
}
export default function ProductPage({ product }) {
return (
<div>
<h1>{product.title}</h1>
<p>{product.description}</p>
</div>
);
}
Key features:
- Automatic code splitting
- Built-in CSS support
- API routes
- Image optimization
- TypeScript support
Gatsby
Gatsby focuses on static site generation but can also perform SSR for dynamic content.
// gatsby-node.js
exports.createPages = async ({ graphql, actions }) => {
const { createPage } = actions;
const result = await graphql(`
query {
allProduct {
nodes {
id
slug
}
}
}
`);
result.data.allProduct.nodes.forEach((product) => {
createPage({
path: `/product/${product.slug}`,
component: path.resolve('./src/templates/product.js'),
context: {
id: product.id,
},
});
});
};
Remix
Remix is a newer framework that focuses on web standards and provides excellent SSR capabilities with built-in data loading patterns.
// app/routes/product/$productId.tsx
export let loader: LoaderFunction = async ({ params }) => {
const product = await getProduct(params.productId);
return json({ product });
};
export default function Product() {
const { product } = useLoaderData();
return (
<div>
<h1>{product.title}</h1>
<p>{product.description}</p>
</div>
);
}
Implementation Considerations
Hydration
After the server sends the rendered HTML, React needs to "hydrate" the page on the client side, attaching event listeners and making the page interactive.
// Client-side hydration
import { hydrateRoot } from 'react-dom/client';
import App from './App';
const container = document.getElementById('root');
hydrateRoot(container, <App />);
State Management
Managing state between server and client requires careful consideration:
// Server-side state injection
const initialState = {
user: await fetchUser(),
products: await fetchProducts(),
};
// Client-side hydration with initial state
const store = createStore(reducer, initialState);
Performance Optimization
- Caching: Implement caching strategies for rendered pages
- Code Splitting: Load only necessary code for each route
- Resource Optimization: Optimize images, fonts, and other assets
- Progressive Enhancement: Ensure the page works without JavaScript
When to Use SSR
SSR is beneficial when:
- SEO is critical for your application
- You need fast initial page loads
- Your content is relatively static or changes infrequently
- You're building content-heavy applications (blogs, e-commerce, news sites)
- Social media sharing is important
SSR might not be necessary when:
- Building internal tools or dashboards
- Your application is highly interactive and dynamic
- SEO isn't a primary concern
- You have a sophisticated caching strategy for client-side rendering
Conclusion
Server-side rendering with React offers significant benefits for performance, SEO, and user experience. While it adds complexity to your application architecture, the improvements in initial page load times and search engine visibility often justify the investment.
Modern frameworks like Next.js, Gatsby, and Remix make implementing SSR much easier than building a custom solution from scratch. Choose the framework that best fits your project requirements and team expertise.
Remember that SSR is one tool in your performance toolkit. Combine it with other optimization techniques like code splitting, lazy loading, and proper caching for the best results.