Server-side rendering (SSR) in a MERN stack application involves rendering the initial HTML on the server rather than the client. This allows for faster page loads
and improved SEO, especially for dynamic content.
In a traditional React application, the client downloads a JavaScript bundle, which generates the HTML on the client-side. However, with SSR, the HTML is pre-generated
on the server, improving the initial load time and making the app crawlable by search engines.
Here’s how SSR works in a MERN stack:
1. A request is made from the client to the server.
2. Node.js receives the request and uses React to generate HTML on the server-side.
3. This HTML is sent to the browser, which displays the content immediately.
4. React rehydrates the app on the client-side, allowing it to behave as a dynamic single-page application.
Benefits of SSR in MERN:
1. Improved performance: Faster page loads, as the HTML is pre-rendered.
2. Better SEO: Search engines can crawl the server-rendered HTML.
3. Enhanced user experience: Users see the content quicker, reducing perceived load time.
Example of SSR in a MERN app:
const express = require('express');
const React = require('react');
const ReactDOMServer = require('react-dom/server');
const App = require('./App'); // React App component
const app = express();
const PORT = 5000;
app.get('/', (req, res) => {
const appString = ReactDOMServer.renderToString(
const html = `
`;
res.send(html);
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Leave a Reply