Skip to main content
FreeAn audit of your Drupal siteA written audit of your Drupal site, within three business days
All articles

Backend & EngineeringOct 22, 202610 min read

Reactive components in Drupal without writing JavaScript

Eric ZsigmondCo-Founder & Senior Frontend Engineer

Most interactive pieces of a Drupal site are small: a filter above a list, a vote, a "save for later" button. Each one usually brings a JavaScript file, an endpoint, and two copies of the same validation. sdx_reactive, one of the modules in our sdx_realtime project, takes a different route. The state and the actions live in a PHP class, the markup lives in a Twig template, and a small runtime that ships with the module connects the two. You write no JavaScript.

In this article we build a topic filter for a list of articles, place it on a page, look at what crosses the wire when someone clicks, and go through how the module keeps the state honest. The examples use the 1.0.x development branches of sdx_realtime and SDX; the plain templates shown here arrive with the next tagged release.

How a reactive component is put together

A reactive component has three parts. The markup is an ordinary single-directory component: a component.yml and a Twig template. The state belongs to a plugin class marked with #[SdxReactive]. Every property marked #[ReactiveState] is handed to the template as a prop, and every public method marked #[ReactiveAction] can be called from the browser. The runtime, js/sdx-reactive.js, finds the component on the page, turns clicks on elements with data-sdx-action into requests, and swaps in the HTML the server returns.

The attribute's transport option decides what comes back. morph returns re-rendered Twig and is the one for PHP-and-Twig components. props hands the new state to a React, Vue, or Svelte component instead. realtime is morph plus polling, for state that every visitor shares. If you know Livewire or Phoenix LiveView, the shape will feel familiar.

The component: markup with action hooks

The component lives in my_module/components/topic-filter/. Its definition declares the state as props, plus the internal props the render pipeline adds:

name: Topic filter
description: Latest articles, filtered by topic on the server.
sdx:
  widget: false
props:
  type: object
  properties:
    topic:
      type: integer
    topics:
      type: array
    items:
      type: array

The schema lists only your own props. SDX adds its own internal props when it renders the component, and Drupal does not ask you to declare them. The sdx: block does matter: SDX treats a component as its own only when that block is not empty, and the reactive step needs that to find its plugin. We copied widget: false from the module's own counter example.

The template is plain Twig with one root element. Buttons bind to an action:

<div class="topic-filter">
  <div class="topic-filter__topics">
    <button type="button" data-sdx-action="filter" data-sdx-params="[0]"
      aria-pressed="{{ topic == 0 ? 'true' : 'false' }}">{{ 'All topics'|t }}</button>
    {% for option in topics %}
      <button type="button" data-sdx-action="filter" data-sdx-params="[{{ option.id }}]"
        aria-pressed="{{ topic == option.id ? 'true' : 'false' }}">{{ option.label }}</button>
    {% endfor %}
  </div>
  <ul class="topic-filter__items">
    {% for item in items %}
      <li><a href="{{ item.url }}">{{ item.title }}</a></li>
    {% else %}
      <li>{{ 'No articles on this topic yet.'|t }}</li>
    {% endfor %}
  </ul>
</div>

data-sdx-action names the PHP method. data-sdx-params is a JSON array, passed to that method as positional arguments. Nothing in the template is about reactivity itself: when the component renders, sdx_reactive puts data-sdx-reactive, the signed state and the component id on the root element, and the runtime reads them from there. A template with several top-level elements gets an <sdx-reactive> wrapper instead, which takes no part in layout.

The plugin: state and actions in PHP

Plugins are discovered in src/Plugin/SdxReactive/. The first half of the class declares the binding, the state, and a dependency:

<?php

declare(strict_types=1);

namespace Drupal\my_module\Plugin\SdxReactive;

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\sdx_reactive\Attribute\ReactiveAction;
use Drupal\sdx_reactive\Attribute\ReactiveState;
use Drupal\sdx_reactive\Attribute\SdxReactive;
use Drupal\sdx_reactive\Plugin\SdxReactivePluginBase;
use Symfony\Component\DependencyInjection\ContainerInterface;

#[SdxReactive(
  id: 'my_module_topic_filter',
  component: 'my_module:topic-filter',
  label: 'Topic filter',
  transport: 'morph',
)]
final class TopicFilter extends SdxReactivePluginBase implements ContainerFactoryPluginInterface {

  #[ReactiveState]
  public int $topic = 0;

  #[ReactiveState]
  public array $topics = [];

  #[ReactiveState]
  public array $items = [];

  public function __construct(array $configuration, $plugin_id, $plugin_definition, private readonly EntityTypeManagerInterface $entityTypeManager) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
  }

  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition): static {
    return new static($configuration, $plugin_id, $plugin_definition, $container->get('entity_type.manager'));
  }

The plugin manager is a standard Drupal plugin manager, so ContainerFactoryPluginInterface works as it does for blocks. The second half holds the behavior. It assumes an article content type with a field_topic reference to a topics vocabulary:

  public function mount(): void {
    $terms = $this->entityTypeManager->getStorage('taxonomy_term')->loadByProperties(['vid' => 'topics']);
    foreach ($terms as $term) {
      $this->topics[] = ['id' => (int) $term->id(), 'label' => (string) $term->label()];
    }
    $this->items = $this->loadItems();
  }

  #[ReactiveAction]
  public function filter(int $topic): void {
    $known = array_column($this->topics, 'id');
    $this->topic = in_array($topic, $known, TRUE) ? $topic : 0;
    $this->items = $this->loadItems();
  }

  private function loadItems(): array {
    $storage = $this->entityTypeManager->getStorage('node');
    $query = $storage->getQuery()
      ->accessCheck(TRUE)
      ->condition('type', 'article')
      ->condition('status', 1)
      ->sort('created', 'DESC')
      ->range(0, 10);
    if ($this->topic > 0) {
      $query->condition('field_topic', $this->topic);
    }
    $items = [];
    foreach ($storage->loadMultiple($query->execute()) as $node) {
      $items[] = ['title' => (string) $node->label(), 'url' => $node->toUrl()->toString()];
    }
    return $items;
  }

}

Three things to notice. mount() runs once, on the first render; after that the plugin is rebuilt from state, so the list of topics travels with the component. That is why filter() can check the requested topic against $this->topics: the browser cannot change that list without breaking the signature, as we will see. loadItems() is private and has no attribute, so it cannot be called from outside. And the query runs with accessCheck(TRUE), because actions run as the visitor who clicked.

Placing it on a page

The plugin binds to the component by id, so anything that renders my_module:topic-filter as a component render element gets the behavior. A block is the simplest way to place it:

<?php

declare(strict_types=1);

namespace Drupal\my_module\Plugin\Block;

use Drupal\Core\Block\Attribute\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\StringTranslation\TranslatableMarkup;

#[Block(
  id: 'my_module_topic_filter',
  admin_label: new TranslatableMarkup('Articles by topic'),
)]
final class TopicFilterBlock extends BlockBase {

  public function build(): array {
    return [
      '#type' => 'component',
      '#component' => 'my_module:topic-filter',
      '#props' => [],
      '#cache' => ['tags' => ['node_list', 'taxonomy_term_list']],
    ];
  }

}

sdx_reactive adds its own pre-render callback to the component element. It mounts the plugin, merges the state into the props, puts the signed payload on the template's root element, attaches the sdx_reactive/runtime library, and puts the endpoints and a CSRF token into drupalSettings. It also adds the session cache context, so each session gets its own render-cached copy. The cache tags in build() are ours: mount() reads content, so the first render should refresh when articles or topics change.

One detail shapes every template. When the server re-renders after an action, the template receives the state and the internal props, nothing else. Props passed in the render array are not part of that context, and mount() takes no arguments. Anything the template prints should be state.

What travels on a click

Clicking "Hosting" sends a POST to /sdx-reactive/update, with the session's token in an X-CSRF-Token header. The body, formatted for reading:

{
  "fingerprint": {
    "id": "my_module_topic_filter",
    "component": "my_module:topic-filter",
    "transport": "morph"
  },
  "state": {
    "topic": 0,
    "topics": [{"id": 5, "label": "Hosting"}, {"id": 8, "label": "Security"}],
    "items": [{"title": "Planning a calm upgrade", "url": "/articles/calm-upgrade"}]
  },
  "checksum": "<HMAC-SHA256 of the state above, 64 hex characters>",
  "calls": [{"method": "filter", "params": [5]}]
}

The server validates the checksum, rebuilds the plugin from the state, runs filter(5), and answers with the effects:

{
  "effects": {
    "state": {
      "topic": 5,
      "topics": [{"id": 5, "label": "Hosting"}, {"id": 8, "label": "Security"}],
      "items": [{"title": "What managed hosting means", "url": "/articles/managed-hosting"}]
    },
    "checksum": "<new HMAC for the new state>",
    "dirty": ["topic", "items"],
    "html": "<div data-sdx-reactive ... class=\"topic-filter\">...</div>"
  }
}

dirty lists the properties that changed. html is the template rendered with the new state; the runtime replaces the component's content with it and runs Drupal behaviors on the result. The new checksum becomes the one the next click sends. If an action calls $this->emit(), the response also carries events, which the runtime dispatches as sdx-reactive: DOM events.

How the state is protected

Everything the browser sends is checked before any of your code runs:

  • The route. Both endpoints accept POST only, require the access content permission, and are refused while enabled is off in sdx_reactive.settings. The controller rejects a missing or wrong CSRF token.
  • The signature. StateChecksum signs the state with HMAC-SHA256, keyed by the site's hash_salt, and compares in constant time. The module refuses to run without a hash_salt. Change one value in the state, or add a topic to the list, and the request fails with a 403.
  • The actions. Only public methods with #[ReactiveAction] can be called; any other name is a 403. Parameters are checked against the method signature: a missing required argument, or a value that does not match a declared scalar type, is a 400. Declare a scalar type on every action parameter, and still check the value inside the action, as filter() does.
  • The template. The template that is re-rendered comes from the plugin whose checksum just validated, never from the request body.

The signature proves the server produced the state. It does not make the state private, and it does not decide who may act on it. Anything in state is readable in the page source, so keep secrets out of it. Check access in mount() and in every action, from the current user and the data, as a controller would, and never from a flag kept in state.

The runtime also has a data-sdx-model binding for inputs, which edits state in the browser before syncing. At this tag, that edited state no longer matches its checksum, so the server answers with a 403. Pass user input as action parameters instead, as filter() does; every change then happens on the server.

Testing the protection

The module's services are plain PHP classes, so the security contract fits in a unit test. This one uses the real StateChecksum and ReactiveStateManager, with no database:

<?php

declare(strict_types=1);

namespace Drupal\Tests\my_module\Unit;

use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Site\Settings;
use Drupal\Core\State\StateInterface;
use Drupal\my_module\Plugin\SdxReactive\TopicFilter;
use Drupal\sdx_reactive\Plugin\SdxReactivePluginManager;
use Drupal\sdx_reactive\Security\StateChecksum;
use Drupal\sdx_reactive\Service\ReactiveStateManager;
use Drupal\Tests\UnitTestCase;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;

/**
 * @group my_module
 */
final class TopicFilterSecurityTest extends UnitTestCase {

  private const STATE = ['topic' => 0, 'topics' => [['id' => 5, 'label' => 'Hosting']], 'items' => []];

  private StateChecksum $checksum;

  private ReactiveStateManager $manager;

  protected function setUp(): void {
    parent::setUp();
    $this->checksum = new StateChecksum(new Settings(['hash_salt' => 'test-salt']));
    $plugin = new TopicFilter([], 'my_module_topic_filter', ['component' => 'my_module:topic-filter'], $this->createMock(EntityTypeManagerInterface::class));
    $plugins = $this->createMock(SdxReactivePluginManager::class);
    $plugins->method('createInstance')->willReturn($plugin);
    $this->manager = new ReactiveStateManager($plugins, $this->checksum, $this->createMock(StateInterface::class), $this->createMock(CacheBackendInterface::class));
  }

  private function send(array $state, array $calls): array {
    return $this->manager->processUpdate([
      'fingerprint' => ['id' => 'my_module_topic_filter'],
      'state' => $state,
      'checksum' => $this->checksum->generate('my_module_topic_filter', self::STATE),
      'calls' => $calls,
    ]);
  }

  public function testTamperedStateIsRejected(): void {
    $tampered = self::STATE;
    $tampered['topics'][] = ['id' => 99, 'label' => 'Internal'];
    $this->expectException(AccessDeniedHttpException::class);
    $this->send($tampered, []);
  }

  public function testPrivateMethodsAreNotCallable(): void {
    $this->expectException(AccessDeniedHttpException::class);
    $this->send(self::STATE, [['method' => 'loadItems', 'params' => []]]);
  }

  public function testParameterTypesAreChecked(): void {
    $this->expectException(BadRequestHttpException::class);
    $this->send(self::STATE, [['method' => 'filter', 'params' => ['5']]]);
  }

}

Each test fails before the plugin touches storage, which is why a mocked entity type manager is enough. The third one sends the topic as the string "5"; the signature says int, so the manager refuses it. The query inside loadItems() deserves a test against a real database, and a kernel test is the right tool for it; we compared the two in kernel tests vs unit tests in Drupal.

When not to use it

Every action is a round trip and a full Drupal request. That is the strength of the model, and also its edge.

  • High-frequency interaction. Dragging, drawing, sliders that update as they move, and anything that reacts to every keystroke need answers in the browser, not from the server. Write those as client components; the props transport can still hand them server state.
  • Offline use. Without the server, nothing changes. A failed request is logged to the console and nothing is queued for later. Interfaces that must work offline belong in client code with their own sync.
  • Anonymous visitors. The update endpoint checks a CSRF token, and Drupal keeps the token's seed in the session. Drupal does not save a session for an anonymous visitor who has nothing else in it, so for most anonymous visitors the token cannot be validated and every action is refused with a 403. The internal page cache would also serve one cached copy of the page to every anonymous visitor. The module fits logged-in areas: member pages, dashboards, editorial tools.
  • Large state. The whole state sits in the page and travels with every request. Keep it to ids and short lists.
  • Per-user data in the realtime transport. That mode stores one copy of the state in Drupal's State API for the whole site and polls for changes. It suits shared values, never personal ones.

For a filter, a vote, or an "add to list" button on a logged-in page, the model is pleasant to work with: one PHP class, one template, and the validation in one place. The code is on the sdx_realtime project page, and the rest of the stack is on our SDX page. If you would like help building something like this into your own site, that is work we do.

Written by

Eric Zsigmond

Co-Founder & Senior Frontend Engineer

Frontend engineer with deep expertise in Drupal theming, component-driven architecture, and modern JavaScript frameworks. Builds fast, accessible interfaces using React, SDX, and Tailwind. Obsessive about performance, pixel-perfect implementation, and clean markup. Almost every pixel on this page is his work.

Enjoyed this article?

If this resonated, imagine what we could do working together on your Drupal site.