Skip to main content

SPA support

In a single-page application the CMP must know about route changes to process new content and track sessions correctly.

Call onRouteChange() from your router's route change handler:

// React Router
useEffect(() => {
OptSens.onRouteChange();
}, [location.pathname]);

// Vue Router
router.afterEach(() => {
OptSens.onRouteChange();
});

// Next.js (Pages Router)
Router.events.on('routeChangeComplete', () => {
OptSens.onRouteChange();
});

// Next.js (App Router), usePathname from 'next/navigation'
const pathname = usePathname();
useEffect(() => {
OptSens.onRouteChange();
}, [pathname]);

Option 2: automatic detection

Detects route changes automatically by patching history.pushState and replaceState and listening for browser back and forward navigation:

OptSens.on('ready', function () {
OptSens.enableSpaAutoDetect();
});

What onRouteChange() does

  1. Re-scans the DOM for new data-os-category elements
  2. Fires the session beacon if the session cookie expired
  3. Pushes an OptSensPageView event to the GTM dataLayer
  4. Emits the route_change event