Direkt zum Inhalt
KostenlosEin Audit deiner Drupal-WebsiteEin schriftliches Audit deiner Drupal-Website, innerhalb von drei Werktagen
Alle Artikel

Backend & Engineering8. Okt. 20269 Min. Lesezeit

React server-side rendering inside Drupal

Eric ZsigmondMitgründer & Senior Frontend Engineer

An SDX component is a React component that Drupal places on a page like any other single directory component. Without server rendering, Drupal sends an empty container plus the props as JSON, and the browser draws the component once its JavaScript has loaded. That works, but the first paint waits for the bundle, and anything that reads the raw HTML sees an empty box.

The sdx_ssr sub-module closes that gap. During the normal page render, Drupal asks a small Node.js process to turn the component into HTML, places that HTML inside the container, and the browser hydrates it instead of drawing it from scratch. Drupal keeps routing, access, caching and the page itself. Node only turns props into markup. The examples use SDX 1.0.0-alpha18, the current release on the 1.0.x branch.

Declaring a component

Nothing about the component is specific to server rendering. It is a standard SDC directory whose .component.yml has an sdx: key naming the framework and the entry file. Here is a small price tag in a custom module:

# my_module/components/price-tag/price-tag.component.yml
name: Price tag
status: stable

sdx:
  framework: react
  entry: PriceTag

props:
  type: object
  properties:
    title:
      type: string
      title: Product name
    price:
      type: string
      title: Formatted price
    details:
      type: string
      title: Details

The entry file exports a default React component. This one keeps a little state, so there is something to hydrate:

// my_module/components/price-tag/PriceTag.tsx
import { useState } from 'react';

interface Props {
  title: string;
  price: string;
  details?: string;
}

export default function PriceTag({ title, price, details }: Props) {
  const [open, setOpen] = useState(false);

  return (
    <div className="price-tag">
      <h3>{title}</h3>
      <p className="price-tag__price">{price}</p>
      {details && (
        <button type="button" onClick={() => setOpen(!open)}>
          {open ? 'Hide details' : 'Show details'}
        </button>
      )}
      {open && <p>{details}</p>}
    </div>
  );
}

Drupal code uses it like any component render element, for example in a block plugin's build() method. The cache tags are ordinary Drupal metadata, and they matter later:

$build['price'] = [
  '#type' => 'component',
  '#component' => 'my_module:price-tag',
  '#props' => [
    'title' => $product->label(),
    'price' => $formatted_price,
    'details' => $summary,
  ],
  '#cache' => [
    'tags' => $product->getCacheTags(),
  ],
];

Notice what is missing: no SSR flag and no special service call. Once sdx_ssr is enabled, every SDX component is server-rendered unless it opts out.

The round trip: what Drupal sends and what comes back

The work happens in pre-render callbacks on Drupal's component element. SDX's own callback runs first. It resolves the component's data, sets _sdx_component_id and encodes the props as JSON. sdx_ssr appends a second callback, SsrComponentPreRender, which passes the component ID, the decoded props and the current language to the sdx_ssr.renderer service. That service sends a POST /render request to the Node process with this body:

{
  "components": [
    {
      "component_id": "my_module:price-tag",
      "props": {
        "title": "Espresso grinder",
        "price": "$249",
        "details": "Conical burrs and a dosing cup.",
        "_sdx_component_id": "my_module:price-tag"
      },
      "langcode": "en"
    }
  ]
}

The server answers with a results list, one entry per component, each with html, error and a cached flag. For React, the renderer that SDX generates calls renderToString from react-dom/server. The props are the same JSON the browser receives, so both sides render from identical input. The callback stores the HTML in the _sdx_ssr_html prop, and SDX's shared mount template prints it inside the container (formatted here for reading):

<div class="sdx-component" data-component="my_module:price-tag" data-eager data-sdx-ssr>
  <script type="application/json" data-sdx-props-for="my_module:price-tag">{"title":"Espresso grinder", ...}</script>
  <div class="price-tag"><h3>Espresso grinder</h3><p class="price-tag__price">$249</p>...</div>
</div>

In the browser, the SDX mount coordinator finds the container, reads the props from the script tag and loads the component bundle. When the container carries data-sdx-ssr, the React adapter calls hydrateRoot instead of createRoot, so React attaches its event handlers to the existing markup rather than replacing it. The visitor sees the price before any JavaScript runs, and the button works as soon as hydration finishes. If the server HTML and the client render disagree, the adapter logs a "Recoverable hydration error" with the component stack, which points at the element that differs.

Themes that render the whole page as one React app, the setup from our sdx_drast article, use a page-level variant. sdx_ssr implements hook_sdx_page_render_alter() and sends the full page data to /render-page. That path is off by default: it needs page_ssr.enabled in the settings and sdx_ssr: true in the theme's info file.

Render cache, SSR caches and cache tags

Because SSR runs inside a pre-render callback, it sits underneath Drupal's render cache rather than beside it. When the component lives inside something Drupal caches, such as a block or an entity view, a render cache hit returns the stored HTML with the server-rendered markup included, and Node is never called. The element's cache tags decide when that stored copy is discarded. When the product is saved, Drupal invalidates its tag, the next request renders the element again, and the new props travel to Node.

Below the render cache, sdx_ssr keeps two layers of its own, both keyed on the props:

  • A Drupal cache bin, sdx_ssr. SsrCacheManager stores each result under ssr:{component}:{md5 of props}:{langcode}, tagged sdx_ssr and sdx_ssr:{component}. It uses the site's cache backend, so it survives Node restarts. Entries live for cache.ttl seconds, an hour by default.
  • An in-memory cache in each Node worker. It holds up to --cache-max entries (1,000 by default) for --cache-ttl seconds (60 by default) and is lost on restart.

Since the props are part of every key, edited content produces a new key rather than a stale hit, and old entries expire on their own. That is what keeps component renders correct. sdx_ssr also registers a cache tags invalidator that forwards each Drupal invalidation to the server's /cache/purge endpoint, with a one-second timeout and failures ignored. At this release, though, component render requests carry no cache tags, so the Node entries they create are never matched by a purge. Treat the purge as plumbing for later, not as part of the correctness story.

When the renderer is unavailable

Server rendering is an improvement, not a dependency. Every failure path in SsrRenderer returns NULL, the container goes out without HTML, and the browser renders the component exactly as it would without sdx_ssr. Three mechanisms stop a missing renderer from slowing pages down:

  • A health check. Before its first uncached render in a request, the renderer calls GET /health with a one-second connect timeout and reuses the answer for the rest of the request.
  • A render timeout. Each render waits at most server.timeout milliseconds, 500 by default.
  • A circuit breaker. Three consecutive failures open the circuit for 30 seconds. The state lives in Drupal's State API, so every PHP worker skips SSR at once instead of each discovering the outage. When the cooldown ends, the failure count is reset and renders are tried again; three more failures in a row open the circuit for another 30 seconds.

A degraded page should not be cached as if it were normal. When SSR was expected and failed, the callback triggers the page cache kill switch and sets max-age to zero on the element where the failure first appeared in that request, so the client-rendered page is not stored in the page caches. Full-page SSR has a stricter option, page_ssr.strict, which answers with a 503 and a 30-second Retry-After so crawlers come back instead of indexing an empty shell. Development mode is a separate case: while drush sdx:dev serves components through Vite, SSR is skipped on purpose and nothing is marked as degraded.

Building, running and checking it

The settings live in sdx_ssr.settings and on the Server-Side Rendering tab of the SDX settings under Configuration, Development, SDX. This excerpt shows the installed defaults:

# sdx_ssr.settings (excerpt of the installed defaults)
enabled: true
server:
  host: '127.0.0.1'
  port: 3010
  timeout: 500
cache:
  enabled: true
  ttl: 3600
page_ssr:
  enabled: false
  timeout: 2000
  strict: false

Two builds feed it. drush sdx:build produces the browser bundles as usual. drush sdx:ssr:build produces Node-compatible CommonJS bundles of the same components, with style imports stubbed out, and writes the framework renderer module the server loads. On the sites we run, the build step runs these in order, and the platform starts the Node process from the output:

# Once per site.
drush en sdx_ssr -y

# Every build.
drush sdx:resolve
drush sdx:build --mode=production
drush sdx:ssr:build --mode=production

# A single server: let Drush start a detached Node process.
drush sdx:ssr:start
drush sdx:ssr:status

# Containers: run the server as its own long-running process next to PHP.
node /path/to/sdx/modules/feature/sdx_ssr/js/ssr-server.mjs \
  --dist-dir=/path/to/dist-ssr \
  --renderer=/path/to/private/sdx/framework-renderer.mjs \
  --node-modules=/path/to/private/sdx/node_modules \
  --port=3010 \
  --workers=auto

drush sdx:ssr:start suits a single machine. It starts one detached Node process, writes a PID file and a log under private://sdx, and sdx:ssr:stop and sdx:ssr:restart manage it. In production we prefer a separate process supervised by the platform. Either way, the server listens on 127.0.0.1, so it has to run next to PHP: on the same machine, or in a container that shares PHP's network. With --workers=auto it forks one worker per CPU and replaces any worker that crashes. A SIGHUP restarts the workers one at a time. The server loads the SSR bundles when it starts and does not watch them in production, so restart it after every sdx:ssr:build.

To check that a page was server-rendered, look at the raw HTML rather than the DOM after JavaScript has run:

# The container should carry data-sdx-ssr.
curl -s https://example.com/products/grinder \
  | grep -o 'data-component="my_module:price-tag"[^>]*'

# From the PHP host: is the renderer up, and how often does it hit its cache?
curl -s http://127.0.0.1:3010/health
drush sdx:ssr:status

A container with data-sdx-ssr and the component's markup inside was rendered on the server. One with only the props script fell back to the browser. The health endpoint reports loaded components, uptime, render counts and the cache hit ratio; with several workers, those figures belong to whichever worker answered. After hydration, the container carries data-sdx-mounted="true". Test on a production build, since SSR is off in development mode.

Trade-offs: memory, cold starts and browser-only code

Memory. Every worker loads all SSR bundles, React and its own render cache, and workers share none of it. On a machine with many cores, --workers=auto multiplies that footprint. Size the worker count to the traffic rather than the core count, and give the Node process its own memory limit so it cannot crowd out PHP.

Cold starts. After a restart the in-memory cache is empty, and the first render of each component pays the full cost. The Drupal-side bin softens this because it survives Node restarts. A render slower than server.timeout falls back to the browser and counts toward the circuit breaker, so a timeout set too tight on a slow machine shows up as client-rendered, uncached pages after each restart. The reverse also applies on deploy. When component markup changes, clear the sdx_ssr bin with a cache rebuild or drush sdx:ssr:clear, and restart the Node server, which empties its own cache and loads the new bundles. sdx:ssr:clear only clears the Drupal bin. Together they keep old HTML from meeting a new bundle.

Browser-only code. Node has no window, document or localStorage. A component that touches them while rendering throws on the server. SDX handles that safely and falls back to the browser, but each such error counts toward the circuit breaker and keeps the page out of the caches. Keep browser APIs inside useEffect, which only runs in the browser. For components that are browser-only by nature, such as a map or a chart that measures the DOM, add ssr: false under the sdx: key of the .component.yml. Opted-out components skip the Node round trip and are not counted as failures. One more detail: path() from @sdx/runtime returns # on the server, because route patterns only exist in the browser, so pass finished URLs in as props.

Page weight. A server-rendered component ships twice, as HTML and as the props JSON the browser needs for hydration. For a price tag that is negligible. For a component fed a long list, check whether the browser really needs all of it.

Server rendering gives SDX components what Twig templates always had, real HTML on the first response, without giving up React in the browser. For whole pages rendered by React, start with the sdx_drast article. The module ships with SDX on drupal.org, and if you would like help running the Node side on your own hosting, get in touch.

SchlagwörterBackendSDXReact

Geschrieben von

Eric Zsigmond

Mitgründer & Senior Frontend Engineer

Frontend-Entwickler mit tiefem Know-how in Drupal-Theming, komponentenbasierter Architektur und modernen JavaScript-Frameworks. Baut schnelle, barrierefreie Interfaces mit React, SDX und Tailwind. Fast jeder Pixel auf dieser Seite stammt von ihm.

Hat dir der Artikel gefallen?

Wenn er dich angesprochen hat: Stell dir vor, was wir gemeinsam aus deiner Drupal-Website machen könnten.