Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

13.1 KB
Raw Blame
---
title: Routes
sidebarTitle: Routes
description: Mount custom pages under your dashboard's `/$storeId/...` path, or outside a store at the root — onboarding, sign-up and account pages. Supports path params, permission gating, and works alongside the dashboard's built-in routes.
---

<Note>
Examples here import from `@spree/dashboard`, which re-exports the framework and the design system for host applications. A **distributed plugin** imports `@spree/dashboard-core` and `@spree/dashboard-ui` directly instead — it extends the shell rather than shipping it. See [plugin overview](/developer/dashboard/plugins/overview).
</Note>

The dashboard's first-party routes (`customers/`, `orders/`, `products/`, …) are file-based via TanStack Router and live in `@spree/dashboard/src/routes/`. Custom pages have two mechanisms:

1. **File routes** (packaged plugins — preferred): the plugin ships ordinary TanStack route files, and the host build compiles them into its typed route tree. Typed `<Link>`s with no casts, route-level code splitting, `validateSearch`, loaders — full router citizenship.
2. **Route registry** (in-app & dynamic): `defineDashboardPlugin({ routes })` entries matched at navigation time by a catch-all dispatcher at `/_authenticated/$storeId/$`. Use for host-app customizations (`plugins.ts`) and anything registered conditionally at runtime. File routes always win over the registry — the catch-all is the lowest-priority match.

## File routes (packaged plugins)

Declare a routes directory in your plugin's marker and put TanStack route files in it:

```jsonc
// package.json
"spree": { "dashboard": { "plugin": true, "routes": "./src/routes" } }
```

```
src/
├── pages/                     # page components
└── routes/
    ├── brands.index.tsx       # → /$storeId/brands
    └── brands.$brandId.tsx    # → /$storeId/brands/br_123
```

```tsx
// src/routes/brands.index.tsx
import { resourceSearchSchema } from '@spree/dashboard'
import { createFileRoute } from '@tanstack/react-router'
import { BrandsListPage } from '../pages/brands-list'

export const Route = createFileRoute('/_authenticated/$storeId/brands/')({
  validateSearch: resourceSearchSchema,
  component: () => <BrandsListPage searchParams={Route.useSearch()} />,
})
```

Rules that make this work:

- **Commit the final composed path literal.** Plugin routes mount under the dashboard's `_authenticated/$storeId` layout; the route generator verifies the literal (and would rewrite a wrong one).
- **The host regenerates its `routeTree.gen.ts` on every dev start and build** from installed package versions — updating your plugin picks up new routes automatically (dev servers need a restart, same as installing a plugin).
- **Exclude `src/routes` from your package's standalone `tsc`** — `createFileRoute` paths only type-check against a generated tree, which exists in host programs. Develop against a dashboard host (the scaffold's tsconfig ships this exclusion).

Links to file routes are fully typed — no casts:

```tsx
<Link to="/$storeId/brands/$brandId" params={{ brandId: brand.id }}>view</Link>
```

### Route collisions

Two packages can't own the same route path. If a plugin declares a path that another plugin — or a built-in dashboard page — already claims, the build fails before generating the tree with an error naming both **packages**, the path, and each file:

```
Dashboard route collision.
Route "/$storeId/brands" is declared by more than one package:
  - @acme/brands: "/_authenticated/$storeId/brands/" (…/node_modules/@acme/brands/src/routes/brands.index.tsx)
  - @other/brands: "/_authenticated/$storeId/brands/" (…/node_modules/@other/brands/src/routes/brands.index.tsx)
```

Rename one of the routes, or drop the plugin that shouldn't own it. (Duplicate paths *within* a single package are reported by the TanStack generator instead — that's an authoring bug in one package.)

<Warning>
The collision check only sees **file routes**. If a store registry route (below) uses the same URL as a compiled file route, there's no build error — the file route silently wins on every navigation, because the registry's catch-all is the lowest-priority match. If a page you registered at runtime never renders, check whether an installed plugin claims the same path.
</Warning>

## Runtime route registry (in-app & dynamic)

Register from your host app's `plugins.ts` (or a plugin that genuinely needs runtime registration):

```tsx
import { defineDashboardPlugin } from '@spree/dashboard'
import { ReportsPage } from './pages/reports'

defineDashboardPlugin({
  routes: [{
    key: 'reports',
    path: '/reports',
    component: ReportsPage,
  }],
})
```

`path` is **relative** to `/$storeId` — the dispatcher prepends the prefix at match time. So `/reports` matches the URL `/store_xyz/reports`. The leading `/` is required.

A registry route can sit under a built-in section, next to its record pages: `/sellers/shopify` renders your page, not a seller whose ID is `shopify`. A registry route wins only where it is more specific than the built-in page — fixed segments beat `$params` — so it can never replace a built-in page at the same path, or claim every record with a pattern such as `/sellers/$id`.

## Pages outside a store

Most pages live inside a store, under `/$storeId`. Some don't belong to one: an onboarding flow, a sign-up page, an account page, terms of service. Both mechanisms can mount pages at the root instead, in one of two scopes:

| Scope | Who can open it | Layout |
|---|---|---|
| `authenticated` | Signed-in users; everyone else goes to the login page | No store sidebar or top bar |
| `public` | Anyone, signed in or not | No store sidebar or top bar |

These pages render on a blank canvas. To match the login page's look, wrap them in `AuthShell` from `@spree/dashboard/components/spree/auth-shell`.

**What these pages can use.** There is no current store here, so anything that reads one is unavailable: `useStore()`, store permissions (`usePermissions()`, `<Can>`), the sidebar and top bar, and the store pages' slots. Everything else works — `useAuth()` (the signed-in user on `authenticated` pages, with the stores they can open in `user.stores`), `adminClient` for calls that don't need a store, i18n, and the `@spree/dashboard-ui` components. On `public` pages nobody may be signed in, so only call endpoints that need no session.

**Reserved paths.** The dashboard owns `/`, `/login`, `/setup`, `/forgot-password`, `/reset-password`, `/accept-invitation/$invitationId` and `/$storeId`. A static path such as `/sign-up` takes priority over `/$storeId`, which means no store can be reached at that path. If a future dashboard release adds a page at a path you use, the build (or, for registry routes, the router) fails with an error naming both, instead of one page silently replacing the other. Prefer specific paths (`/sign-up`, `/account`) over generic ones.

**Keep them out of the main bundle.** A sign-up page is opened by people who never see the rest of the dashboard. Load the page component on demand: `lazyRouteComponent(() => import('../pages/sign-up'), 'SignUpPage')` from `@tanstack/react-router` in a file route, or `lazy(() => import('./pages/sign-up'))` from React as a registry route's `component`.

### File routes

Declare a separate directory per scope in your plugin's marker, next to `routes`:

```jsonc
// package.json
"spree": {
  "dashboard": {
    "plugin": true,
    "routes": "./src/routes",                       // → /$storeId/...
    "authenticatedRoutes": "./src/account-routes",  // → /... (signed in)
    "publicRoutes": "./src/public-routes"           // → /... (anyone)
  }
}
```

The committed path literal follows the same rule as store routes — it is the composed path. Signed-in pages sit inside the dashboard's `_authenticated` layout; public pages sit at the root:

```tsx
// src/account-routes/account.tsx → /account
export const Route = createFileRoute('/_authenticated/account')({ component: AccountPage })

// src/public-routes/sign-up.tsx → /sign-up
export const Route = createFileRoute('/sign-up')({ component: SignUpPage })
```

The [collision check](#route-collisions) compares the URL each route serves, so a plugin's `/sign-up` that clashes with another plugin's — or a signed-in `/account` that clashes with a public `/account` — fails the build with both packages named. Built-in pages such as `/login` and the signed-in landing page at `/` can't be claimed; to change the landing page, register on the [`store_selection` slot](/developer/dashboard/slots-catalog#store_selection) instead.

### Registry routes

Give the entry a `scope`. Its `path` is then the full URL path, not one relative to `/$storeId`:

```tsx
defineDashboardPlugin({
  routes: [
    { key: 'sign-up', scope: 'public', path: '/sign-up', component: SignUpPage },
    { key: 'account', scope: 'authenticated', path: '/account', component: AccountPage },
  ],
})
```

The component receives `params` and `searchParams`, but no `storeId`. `subject` isn't available: permissions belong to a store.

Unlike store routes, these become real routes when the router is built, so register them before `createDashboardRouter` runs. Your `plugins.ts` and every installed plugin already are — `main.tsx` imports them first. A path already used by a dashboard page or another root registry route throws when the router is built, naming the route's `key`.

## Path parameters

TanStack-Router-style `$name` tokens match a single non-empty segment:

```tsx
routes: [
  { key: 'report-detail', path: '/reports/$reportId', component: ReportDetailPage },
  { key: 'report-export', path: '/reports/$reportId/export', component: ReportExportPage },
],
```

## Receiving params

Your component receives three props from the dispatcher:

```tsx
interface PluginRouteProps {
  /** Path params extracted from the URL. Keys match the `$name` tokens in your path. */
  params: Record<string, string>
  /** Always set — every route is scoped to a store. */
  storeId: string
  /** URL search-state. Pass to `<ResourceTable searchParams={searchParams} />` so filters
   *  round-trip through the URL. */
  searchParams: Record<string, unknown>
}

function ReportDetailPage({ params, storeId, searchParams }: PluginRouteProps) {
  const reportId = params.reportId
  // ...
}
```

`searchParams` is typed as `Record<string, unknown>` because the dispatcher can't statically know your page's shape. If you're handing it to `<ResourceTable>`, cast to `ResourceSearch`:

```tsx
import type { ResourceSearch } from '@spree/dashboard'

<ResourceTable searchParams={searchParams as ResourceSearch} ... />
```

## Permission gating

A `subject` on the route entry renders a 403 fallback (instead of the page) when the user lacks `read` permission:

```tsx
routes: [{
  key: 'reports',
  path: '/reports',
  component: ReportsPage,
  subject: 'order',
}],
```

Always pair this with a matching `subject` on the **nav entry** so users without permission never see the link in the first place. The route subject is the defensive layer for direct URLs.

`subject` is a **registry-route** feature — the dispatcher applies it before rendering. File routes don't pass through the dispatcher, so they gate themselves: check permissions inside the component with `<Can>` or `usePermissions()` from `@spree/dashboard-core` and render a fallback. Either way, this is UX only — the backend still authorizes every API call.

## Layout

Store routes inherit the dashboard's `_authenticated` + `$storeId` layout (auth guard, sidebar, top bar, etc.) — your component renders inside the `<Outlet />`. Use `<ResourceLayout>` to get the same header/main/sidebar grid as core pages:

```tsx
import { PageHeader, ResourceLayout } from '@spree/dashboard'

function ReportsPage() {
  return (
    <ResourceLayout
      header={<PageHeader title="Reports" backTo="dashboard" />}
      main={<ReportsList />}
      sidebar={<ReportsFilters />}
    />
  )
}
```

## Linking to a registry route

Registry routes aren't in the generated route tree, so links to them bypass static checking:

```tsx
import { Link } from '@tanstack/react-router'

<Link
  to={'/$storeId/reports/$reportId' as string}
  params={{ storeId, reportId } as never}
>
  View report
</Link>
```

The casts bypass TanStack Router's static type-checking (custom routes aren't in the generated route tree, so neither the path nor its params exist as types). Params are passed as a keyed object — each key fills the matching `$name` token.

## Order of operations

Routes register at module-load time. The dispatcher reads from the registry on **every navigation**, so route registration is much more forgiving than nav: even a route registered after first render works as soon as the user navigates to it. The only ordering rule is the usual i18n one — register your translation bundle above any registration that calls `i18n.t(...)` (see [Translations](/developer/dashboard/customization/translations)).

## Reference

- [`RouteEntry`](https://github.com/spree/spree/blob/main/packages/dashboard-core/src/lib/route-registry.ts) — full type
- [Catch-all dispatcher source](https://github.com/spree/spree/blob/main/packages/dashboard/src/routes/_authenticated/$storeId/$.tsx) — see how matching works