Skip to content

@xmachines/play-tanstack-solid-router

API / @xmachines/play-tanstack-solid-router

TanStack Solid Router adapter for XMachines Universal Player Architecture

License: MIT Version

This package integrates TanStack Solid Router with the TC39 Signals. The logic then drives the navigation through the Solid.js reactivity.

Overview

@xmachines/play-tanstack-solid-router connects a Play actor to TanStack Solid Router through TanStackSolidRouterBridge.

The bridge extends RouterBridgeBase from @xmachines/play-router. Each adapter therefore behaves in the same way in every framework:

  • The actor route signal (actor.currentRoute) drives the router navigation.
  • Each router history event sends a play.route intent to the actor.
  • The actor keeps the ownership of each guarded state transition (Actor Authority).
  • RouterBridgeBase stops a circular update.

Installation

Terminal window
pnpm add @tanstack/solid-router solid-js
pnpm add @xmachines/play-tanstack-solid-router @xmachines/play-router

Peer dependencies:

  • @tanstack/solid-router ^1.168.7
  • solid-js ^1.8.0
  • xstate ^5.31.0

Current Exports

  • TanStackSolidRouterBridge — the primary adapter class
  • PlayRouterProvider — the Solid component that manages the bridge lifecycle
  • PlayRouterProviderProps, TanStackRouterInstance (types)
  • PlayActor — the canonical actor shape (AbstractActor & Routable & Viewable) from @xmachines/play-router. Use it for the type of a renderer callback of PlayRouterProvider
  • RoutableActor — the deprecated alias of PlayActor. Use PlayActor from @xmachines/play-router
  • RouteMap, createRouteMap, RouteMapping, RouteMapOptions (re-exported from @xmachines/play-router)
  • TanStackRouterLike (type)
  • RouterBridge, PlayRouteEvent (types)

URLPattern Support

This package matches each route pattern with the URLPattern API, through @xmachines/play-router.

URLPattern is native in Node.js 24+ and in a modern browser (Chrome 95+, Firefox 117+, Safari 16.4+). In an older environment, load a polyfill before you import this package. See @xmachines/play-router for the details.

Quick Start

import { createRouter, createRootRoute, createRoute } from "@tanstack/solid-router";
import { createMachine } from "xstate";
import { definePlayer, formatPlayRouteTransitions } from "@xmachines/play-xstate";
import { extractMachineRoutes, getRoutableRoutes } from "@xmachines/play-router";
import { TanStackSolidRouterBridge, createRouteMap } from "@xmachines/play-tanstack-solid-router";
const machine = createMachine(
formatPlayRouteTransitions({
id: "app",
initial: "home",
states: {
home: { id: "home", meta: { route: "/" } },
about: { id: "about", meta: { route: "/about" } },
},
}),
);
const routeMap = createRouteMap(machine);
// Mirror the machine's routable states as TanStack routes
const rootRoute = createRootRoute();
const tanstackRoutes = getRoutableRoutes(extractMachineRoutes(machine)).map((route) =>
createRoute({
getParentRoute: () => rootRoute,
path: route.fullPath.replace(/:(\w+)/g, "$$$1"),
component: () => null,
}),
);
const router = createRouter({ routeTree: rootRoute.addChildren(tanstackRoutes) });
const actor = definePlayer({ machine })();
actor.start();
const bridge = new TanStackSolidRouterBridge(router, actor, routeMap);
bridge.connect();
// later
bridge.disconnect();

Solid convenience wrapper

Use PlayRouterProvider when you want a component to manage the bridge lifecycle:

import { PlayRouterProvider } from "@xmachines/play-tanstack-solid-router";
import { RouterProvider } from "@tanstack/solid-router";
// actor, router, and routeMap from the Quick Start above
<PlayRouterProvider
actor={actor}
router={router}
routeMap={routeMap}
renderer={(currentActor, currentRouter) => (
<RouterProvider router={currentRouter}>{/* your app here */}</RouterProvider>
)}
/>;

API

TanStackSolidRouterBridge

The primary adapter class. It extends RouterBridgeBase.

class TanStackSolidRouterBridge {
constructor(router: TanStackRouterLike, actor: RoutableActor, routeMap: RouteMap);
connect(): void;
disconnect(): void;
dispose(): void; // alias for disconnect()
}

Behavior:

  • connect() — subscribes to router.history, sets the actor state from router.history.location for a deep link, and then watches actor.currentRoute for a state-driven navigation.
  • disconnect() — cancels the subscription to the history and stops all the synchronization.
  • It navigates with router.navigate({ to: path }).
  • It subscribes with router.history.subscribe. This covers PUSH, POP, BACK, FORWARD, REPLACE, and GO, and it works when no <RouterProvider> is mounted.

PlayRouterProvider

This Solid component creates a TanStackSolidRouterBridge, connects it, and cleans it up for you.

interface PlayRouterProviderProps<TActor extends PlayActor = PlayActor> {
/** The actor to sync with TanStack Solid Router. */
actor: TActor;
/** The TanStack Router instance returned by `createRouter`. */
router: TanStackRouterInstance;
/** Bidirectional route map for state ID ↔ URL path lookups. */
routeMap: RouteMap;
/** Renderer callback receives the same concrete actor type that was passed in. */
renderer: (actor: TActor, router: TanStackRouterInstance) => JSX.Element;
}

The component creates the bridge synchronously, during its own evaluation, because this is the execution model of Solid. It disconnects the bridge in onCleanup, when Solid disposes of the component.

RouteMap and createRouteMap

These two exports map each state ID to a URL path, and each URL back to a state ID.

const routeMap = new RouteMap([
{ stateId: "home", path: "/" },
{ stateId: "profile", path: "/profile/:userId" },
{ stateId: "settings", path: "/settings/:section?" },
]);
routeMap.getStateIdByPath("/profile/123"); // "profile"
routeMap.getPathByStateId("home"); // "/"
routeMap.getStateIdByPath("/unknown"); // null

Or build from a machine directly:

import { createRouteMap } from "@xmachines/play-tanstack-solid-router";
const routeMap = createRouteMap(machine); // machine: your routable machine (states carry meta.route)

getStateIdByPath returns null, not undefined, for a path that it cannot match.

Usage Patterns

Dynamic Routes with Parameters

const routeMap = new RouteMap([
{ stateId: "post", path: "/users/:userId/posts/:postId" },
{ stateId: "settings", path: "/settings/:section?" },
]);
// Params are extracted and forwarded in the play.route event:
// { type: "play.route", to: "#post", params: { userId: "123", postId: "456" }, query: {} }

Protected Routes and Guards

The auth guards are inside the state machine only. Unauthorized content therefore never appears, not even for a moment:

const machineConfig = {
states: {
dashboard: {
meta: { route: "/dashboard" },
always: {
guard: ({ context }) => !context.isAuthenticated,
target: "login",
},
},
},
};

A user navigates to /dashboard, and the user is not authenticated:

  1. TanStack Router updates the location.
  2. The bridge receives the change and sends play.route to the actor.
  3. The actor evaluates the guard. The guard refuses the transition, and the actor moves to login.
  4. The bridge reads the new actor route (/login).
  5. The bridge calls router.navigate({ to: "/login" }).

Full App Example

import { createRouter, RouterProvider, createRootRoute, createRoute } from "@tanstack/solid-router";
import { onCleanup } from "solid-js";
import { PlayRouterProvider, createRouteMap } from "@xmachines/play-tanstack-solid-router";
import { definePlayer } from "@xmachines/play-xstate";
import { extractMachineRoutes, getRoutableRoutes } from "@xmachines/play-router";
import { authMachine } from "./auth-machine.js"; // your routable machine (states carry meta.route)
const createPlayer = definePlayer({ machine: authMachine });
const actor = createPlayer();
actor.start();
const routeMap = createRouteMap(authMachine);
const routeTree = extractMachineRoutes(authMachine);
const routes = getRoutableRoutes(routeTree);
const rootRoute = createRootRoute({
component: () => {
onCleanup(() => actor.stop());
return (
<PlayRouterProvider
actor={actor}
router={router}
routeMap={routeMap}
renderer={(currentActor, currentRouter) => (
/* your shell/renderer here */
<div />
)}
/>
);
},
});
const tanstackRoutes = routes.map((route) =>
createRoute({
getParentRoute: () => rootRoute,
path: route.fullPath.replace(/:(\w+)/g, "$$$1"),
component: () => null,
}),
);
export const router = createRouter({ routeTree: rootRoute.addChildren(tanstackRoutes) });
export default function App() {
return <RouterProvider router={router} />;
}

Architecture

Bridge-first data flow:

  1. RouterBridgeBase.connect() does the first synchronization between the actor and the router. It sends both the pathname and the query string of router.history.location to the actor.
  2. Each actor route update, through the actor.currentRoute signal, calls the TanStack navigation (router.navigate({ to })).
  3. The bridge subscribes to the TanStack history updates. It converts each update into a play.route event, then sends the event to the actor.
  4. The guards of the actor accept or refuse each transition. The infrastructure reflects the state that results.

The routing infrastructure therefore stays passive, and the state machine keeps the control of the business logic.

Testing

Run tests for this package in isolation:

Terminal window
pnpm --filter @xmachines/play-tanstack-solid-router test

Or from the package directory:

Terminal window
pnpm test

Browser tests (test/browser/**/*.browser.test.ts) run in real Chromium through Playwright. They cover the asynchronous sequences that jsdom cannot reproduce: BACK and FORWARD navigation through router.history.subscribe, echo suppression under real microtask timing, the check of each navigate({ to }) call, and subscriber teardown on disconnect() and on dispose().

Terminal window
# Run browser tests only
pnpm exec vitest --config vitest.browser.config.ts --project play-tanstack-solid-router-browser

Coverage thresholds: lines 80%, functions 80%, branches 70%, statements 80%.

Learn More

License

MIT — see LICENSE.

Classes

Interfaces

Type Aliases

Variables

Functions