Ugrás a tartalomra
IngyenesAudit a Drupal-oldaladrólÍrásos audit a Drupal-oldaladról, három munkanapon belül
Összes cikk

Backend és fejlesztés2026. okt. 15.10 perc olvasás

Instant page changes without a decoupled frontend

Eric ZsigmondTársalapító és senior frontend fejlesztő

Single-page applications feel fast because a click does not throw the page away: only the part that changes is replaced. A decoupled frontend is one way to get that feel. It also brings a second application with its own routing, menus and forms to build and keep in step with Drupal.

sdx_router gets the same feel while Drupal keeps every job it already does well. Drupal still resolves each URL, checks access and renders the page. The router only changes how the browser moves between pages: it intercepts internal link clicks, fetches the next page as JSON, loads any new CSS and JavaScript, and updates the page in place. If you have used Turbo in Rails, the idea will feel familiar. The examples use SDX 1.0.0-alpha18, the current release on the 1.0.x branch.

What stays on the server

sdx_router is a sub-module of SDX and depends on sdx_drast, the theme engine from our sdx_drast article. It attaches its library only when the active theme's engine is drast, because it updates pages from the structured page data that engine produces. Pages rendered by a Twig theme, such as the admin theme, behave exactly as before.

A navigation is an ordinary GET to the real URL, marked as a navigation by a request header. Drupal routes it and checks access as usual, and one of two subscribers turns the result into JSON instead of a document. For routes backed by an SDX data provider, SpaNavigationSubscriber builds the page data directly from the controller result. Every other route, forms included, renders through Drupal's normal HTML pipeline, and PartialResponseSubscriber then takes the page data out of the rendered response. Either way the browser gets the page data, drupalSettings, and the stylesheet and script URLs the page needs, flagged with X-SDX-Partial: 1.

The browser also sends X-SDX-Ajax-Libraries, the compressed list of libraries it has already loaded. A small middleware, SdxAjaxLibrariesHeader, hands that list to Drupal core's ajax_page_state handling, the same mechanism Drupal's AJAX framework uses, so the response leaves out libraries the page already has. The first visit is still a full HTML page, server-rendered if you followed our article on server-side rendering. Every page change after that is JSON, rendered in the browser by the theme's app.

Turning it on

Enable the module with drush en sdx_router -y, then switch navigation on, either on the Navigation tab of the SDX settings or in configuration. The keys live in sdx.settings:

# sdx.settings (navigation keys)
navigate:
  enabled: true
  selector: '[role="main"], main, .layout-content'
  prefetch_delay: 65
  intercept_forms: true
  batch_modal: true

enabled is off by default. selector names the content region that is replaced when a response arrives as plain HTML rather than JSON, first match wins. prefetch_delay is how many milliseconds a pointer must rest on a link before the router prefetches it. It must be positive: at this version, 0 falls back to 65 rather than turning prefetching off, so use the data-sdx-prefetch attribute shown below for that. intercept_forms routes ordinary POST forms through the same engine, and batch_modal shows Drupal batch operations in an in-page progress modal instead of leaving the page.

Which links it takes over

The policy is conservative. The click listener runs in the capture phase and takes a link only when all of these hold:

  • It is a plain left click, without Ctrl, Cmd, Shift or Alt.
  • The link points to the same origin, has no target="_blank", no download attribute and no use-ajax class.
  • It is not a jump to an anchor on the current page.
  • Its path does not match the exclude pattern, which by default covers /batch and /user/{id}/edit.
  • Neither the link nor any ancestor carries data-sdx-navigate="false".

Admin paths are not on that list at this version. A link from the site into the admin area is fetched like any other, the router sees that the response comes from a different theme, and it falls back to a full load. That works, at the cost of a second request, so mark admin links in your front-end theme with data-sdx-navigate="false".

Forms follow the same spirit: only same-origin, non-multipart submissions are intercepted, and file uploads always submit natively. The attributes give you control per link or per region:

<!-- Always a full page load. -->
<a href="/downloads/catalog" data-sdx-navigate="false">Catalog</a>

<!-- Links and forms inside this region keep their native behavior. -->
<div class="partner-widget" data-sdx-navigate="false">
  ...
</div>

<!-- Navigates in place, but is never prefetched on hover. -->
<a href="/reports/live" data-sdx-prefetch="false">Live report</a>

<!-- Treated as a change within the page: no progress bar, no scroll to top. -->
<a href="/products?sort=price" data-sdx-scope="content">Sort by price</a>

Links inside a .pager or a table header get the content scope automatically, as does any link to the current path with a different query string. Everything else is a full page change.

Prefetching, swapping and the progress bar

When the pointer rests on a link for prefetch_delay milliseconds, the router starts fetching it with its navigation headers. Moving away does not cancel a fetch that has started. When the click comes, the router uses the finished response or waits for the one in flight, so a hover-then-click often feels immediate. Links with a token query parameter, such as CSRF-protected action links, are never prefetched, because a prefetch would spend the one-time token.

When a response arrives, the router works through a fixed sequence:

  1. If the response comes from a different theme, it does a normal full load instead, because the two page shells do not match.
  2. It updates document.title and merges the new drupalSettings.
  3. It loads stylesheets it has not seen in parallel and new scripts one after another, keeping type="module" where a library declares it.
  4. It moves the is-active and menu-item--active-trail classes to the links for the new URL.
  5. It publishes the new page data, and the theme's app renders it.

When the response is plain HTML instead, the router replaces the children of the content region, detaches and re-attaches Drupal behaviors, and wraps the swap in a View Transition where the browser supports one. On both paths, the title is the only part of the document head the router updates. Meta tags and links in the head keep the first page's values, which matters to any script that reads them after a page change.

For page changes, a three-pixel progress bar runs along the top of the window. It is plain markup with the classes sdx-navigate-bar and sdx-navigate-bar__fill, so a theme can restyle it in CSS. Changes within the page skip it. Code can start a navigation too: Drupal.sdxNavigation.navigate(url, { scope: 'content' }) returns a promise for the final state, and Drupal.sdxNavigation.prefetch(url) warms the cache.

If anything goes wrong, such as a network error or a response that is not a 2xx, the router falls back to a full browser load of the same URL. A 404 therefore shows Drupal's real 404 page.

Scroll, history and unsaved changes

The router writes the history entry before it fetches, so the address bar shows the destination right away. Each new navigation aborts the previous fetch, and a late response from a superseded navigation is dropped, so quick clicks never show pages out of order. After a page change the window scrolls to the top, while changes within the page keep the scroll position. On the HTML path, the router scrolls smoothly to the target of the URL's hash, or to the top when there is none.

Back and forward are handled through popstate: the router fetches the URL the browser moved to without adding a new entry, then treats it like any other navigation. Going back to a different path therefore scrolls to the top; at this version the previous scroll position is not restored.

If the page holds an element with the class sdx-editing, the router asks for confirmation before leaving, for clicks and for the back button alike. It uses SDX's dialog when that library is loaded and the browser's own confirm otherwise. A module with an inline editor only needs to toggle that class.

Listening to navigation events

The router dispatches three events on document. They fire for clicks, for back and forward, for programmatic calls, and for form submissions that land on a new page. This listener marks the page as busy and reports a page view to a tag manager that reads a dataLayer:

document.addEventListener('sdx:navigate-start', (event) => {
  // event.detail: { path, url, id, scope, staleKeys }
  document.documentElement.classList.add('is-navigating');
});

document.addEventListener('sdx:navigate-end', () => {
  document.documentElement.classList.remove('is-navigating');

  // The address bar and the title already show the new page here.
  window.dataLayer = window.dataLayer || [];
  window.dataLayer.push({
    event: 'sdx_page_view',
    page_location: window.location.href,
    page_title: document.title,
  });
});

document.addEventListener('sdx:navigate-error', (event) => {
  // event.detail: { path, error, id }; path holds the full URL here.
  // A full page load follows.
  document.documentElement.classList.remove('is-navigating');
});

Notice that sdx:navigate-end does not fire on the first page load. That one is a real load, and your analytics already counts it. If you prefer a store to events, Drupal.sdxNavigation.subscribe(listener) hands you every state change, with status set to idle, loading or error, and returns an unsubscribe function. Drupal.sdxNavigation only exists on pages where the router runs, so guard for it. The DOM events need no such check.

Making your module's scripts work after a swap

Two facts shape module JavaScript under the router. First, a script file is evaluated once per document, the first time its library arrives. Code at the top level, and listeners for DOMContentLoaded or load, never run again on later pages. Second, after each page change the new content goes through Drupal.attachBehaviors(). SDX's React app shell, DrupalApp, calls it on its main content element once the new page has rendered, and the HTML path calls it on the swapped region. So the rule is the one Drupal has always recommended: do DOM work in a behavior, scoped to context, and guard it with once().

Attach the library from the render array that outputs the markup, with $build['#attached']['library'][] = 'my_module/gallery';. The library then appears in that page's response, and the router loads it the first time a visitor reaches such a page through navigation:

# my_module.libraries.yml
gallery:
  js:
    js/gallery.js: {}
  dependencies:
    - core/drupal
    - core/once

The behavior binds listeners to each gallery element and keeps document-level work to a single binding:

// my_module/js/gallery.js
(function (Drupal, once) {
  Drupal.behaviors.myModuleGallery = {
    attach(context) {
      // Runs on the first load and again after every page change.
      once('my-module-gallery', '.my-gallery', context).forEach((gallery) => {
        gallery.addEventListener('click', (event) => {
          const thumb = event.target.closest('[data-full]');
          if (thumb) {
            gallery.querySelector('.my-gallery__stage').src = thumb.dataset.full;
          }
        });
      });

      // Document-level listeners: once per document, not once per page.
      once('my-module-gallery-keys', 'html').forEach(() => {
        document.addEventListener('keydown', closeZoomOnEscape);
      });
    },
  };

  function closeZoomOnEscape(event) {
    if (event.key === 'Escape') {
      document.querySelectorAll('.my-gallery.is-zoomed')
        .forEach((gallery) => gallery.classList.remove('is-zoomed'));
    }
  }
})(Drupal, once);

Listeners on the gallery element disappear with the element when the next page replaces it. The document listener is bound once and looks the galleries up when it runs. If a behavior starts timers or observers, stop them on sdx:navigate-start. Do not rely on detach alone: the theme's app detaches with the serialize trigger and the HTML path with unload.

Trade-offs and when to opt out

Third-party scripts that expect full page loads. Embed snippets often initialize once on load and read the URL a single time: chat widgets, booking forms, some consent and testing tools. Under the router they keep running with the first page's state. If a script offers an API to re-initialize, call it from sdx:navigate-end. If it does not, put data-sdx-navigate="false" on the links that lead to its pages, so those arrive with a full load.

Analytics page views. A tag that fires on page load counts only the first page of a visit. Send later page views from sdx:navigate-end, as above, or use your tool's history-change trigger, but not both, or every page change counts twice. If you use the history trigger, note that the router writes the history entry before it fetches the page, so at that moment document.title still holds the previous page's title.

Prefetching is real server work. Every hover that outlasts the delay is a full request through Drupal. A prefetched response is used whenever the click comes, even long after the hover, so for pages that change by the minute, add data-sdx-prefetch="false". GET links with side effects should not be links at all, but if you have one, opt it out of prefetching too.

Development mode. While a framework runs through the Vite dev server, HTML swaps fall back to full loads, because hot module replacement cannot survive a DOM swap. Test navigation on a production build.

The router is a small layer on top of the Drupal you already run: the same routes, the same access rules, the same caches, with page changes that feel instant. It pairs naturally with server-side rendering, which makes the first load fast as well. Both ship with SDX on drupal.org. If you are weighing this approach against a decoupled build, we are happy to talk it through.

A szerző

Eric Zsigmond

Társalapító és senior frontend fejlesztő

Frontend fejlesztő, aki otthonosan mozog a Drupal-témák fejlesztésében, a komponensalapú felépítésben és a modern JavaScript-keretrendszerekben. React, SDX és Tailwind segítségével épít gyors, akadálymentes felületeket. Fontos számára a teljesítmény, a pixelpontos kivitelezés és a tiszta kód. Ezen az oldalon szinte minden pixel az ő keze munkája.

Tetszett a cikk?

Ha ez közel áll hozzád, képzeld el, mire jutnánk együtt a Drupal oldaladon.