Sobes.tech
Middle

How does server-side rendering (SSR) technology work?

sobes.tech AI

Answer from AI

Server-Side Rendering (SSR) is a technique where the initial display of a web page occurs on the server rather than in the user's browser.

In traditional client-side rendering, the browser receives an empty HTML file with a link to JavaScript. The browser loads, parses, and executes the JavaScript, then dynamically constructs the DOM and displays the content.

With SSR, the server processes the application's components, generates the complete HTML code, and sends it to the browser.

Stages of SSR:

  1. Request: The user's browser sends an HTTP request to the server.
  2. Server-side rendering: The server runs the application's JavaScript code, including the UI rendering logic, and obtains a fully formed HTML string.
  3. Response: The server sends this HTML file to the browser.
  4. Initial display: The browser receives the HTML and immediately displays the page content, as all elements are already present in the markup.
  5. Hydration: After loading the HTML, the browser loads and executes the application's JavaScript code. This code "brings to life" the static markup, adding interactivity, event handlers, and binding state.

Advantages of SSR:

  • Improved SEO: Search engines better index pages with fully formed HTML.
  • Faster First Contentful Paint (FCP): Users see the page content quicker.
  • Better accessibility for low-end devices and slow internet: Less dependence on client device performance for displaying main content.

Disadvantages of SSR:

  • Increased server load: The server performs more computations for rendering.
  • Development complexity: Requires handling isomorphic code (code that can run on both server and client).
  • Larger response size: The initial server response contains the full HTML.
// Client-side code example (pseudo-code)
// A typical client application receives an empty div
const appDiv = document.getElementById('app');
// JavaScript loads and creates content
appDiv.innerHTML = `<h1>Hello, world!</h1>`;

// Server-side code example (pseudo-code using a framework)
// With SSR, the server generates full HTML
import ReactDOMServer from 'react-dom/server';
import App from './App';

const html = ReactDOMServer.renderToString(<App />);
// The server sends something like:
// <div id="app"><h1>Hello, world!</h1></div>