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

Current Exports

  • TanStackSolidRouterBridge — the primary adapter class
  • PlayRouterProvider — the Solid component that manages the bridge lifecycle
  • PlayRouterProviderProps, TanStackRouterInstance (types)
  • RoutableActor — currentRoute, initialRoute and send, from @xmachines/play-router. It names no view: routing implies no rendering. A renderer callback that reads currentView declares its own actor type, and the constraint keeps it whole
  • RouteMap, RouteMapping, RouteMapOptions (re-exported from @xmachines/play-router)
  • createRouteMap (re-exported from @xmachines/play-router/xstate)
  • TanStackRouterLike (type)
  • RouterBridge, PlayRouteEvent (types)

Quick Start

import { createRouter, createRootRoute, createRoute } from "@tanstack/solid-router";
import { createMachine } from "xstate";
import { definePlayer, compose, PlayerActor } from "@xmachines/play-xstate";
import { formatPlayRouteTransitions, withRouting } from "@xmachines/play-xstate/routing";
import { extractMachineRoutes, getRoutableRoutes } from "@xmachines/play-router/xstate";
import { TanStackSolidRouterBridge } from "@xmachines/play-tanstack-solid-router";
import { createRouteMap } from "@xmachines/play-router/xstate";
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) });
// The bridge needs the routing capability
const actor = definePlayer({ machine, actor: compose(PlayerActor, withRouting) })();
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;
}

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.
  • It waits for the router.load() of a history event before it synchronizes the actor. A mounted <RouterProvider> defers the refresh of router.latestLocation, and without the wait TanStack drops the corrective navigation for a refused URL. See the @xmachines/play-tanstack-router README for the details.

PlayRouterProvider

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

interface PlayRouterProviderProps<TActor extends RoutableActor = RoutableActor> {
/** 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 of @xmachines/play-router/xstate

They map each state ID to a URL path, and each URL back to a state ID. This package exports RouteMap, and it re-exports createRouteMap never: the barrel names no state machine.

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-router/xstate";
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 } from "@xmachines/play-tanstack-solid-router";
import { createRouteMap } from "@xmachines/play-router/xstate";
import { definePlayer, compose, PlayerActor } from "@xmachines/play-xstate";
import { withRouting } from "@xmachines/play-xstate/routing";
import { extractMachineRoutes, getRoutableRoutes } from "@xmachines/play-router/xstate";
import { authMachine } from "./auth-machine.js"; // your routable machine (states carry meta.route)
const createPlayer = definePlayer({
machine: authMachine,
actor: compose(PlayerActor, withRouting),
});
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.

Learn More

License

MIT — see LICENSE.

Classes

Interfaces

Type Aliases

Variables

Functions