Sobes.tech
Junior — Middle

Can you explain how server-side rendering (SSR) works?

sobes.tech AI

Answer from AI

Server-Side Rendering (SSR) is the process of generating an HTML page on the server rather than in the client's browser. Instead of sending an empty HTML and loading JavaScript to build the interface on the client (as in SPA), the server immediately returns a fully formed page.

Advantages of SSR:

  • Fast initial rendering, which improves user experience.
  • Better indexed by search engines.
  • Suitable for applications with dynamic content.

Example in Node.js using Express and React:

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 appString = ReactDOMServer.renderToString(<App />);
  res.send(`
    <!DOCTYPE html>
    <html>
      <head><title>SSR Example</title></head>
      <body>
        <div id="root">${appString}</div>
        <script src="bundle.js"></script>
      </body>
    </html>
  `);
});

app.listen(3000);

Here, the React component is rendered on the server into an HTML string, which is immediately sent to the client.