Skip to content

Routing ​

Sprig provides manual routing with createRouter and Vite file-based routing with createFileRouter. Both are client-side routers, supplied by the optional sprig-framework/router add-on rather than the core runtime.

File-based routes ​

The project demo discovers .sprig pages with Vite's import.meta.glob:

js
import { createFileRouter } from 'sprig-framework/router';

const router = createFileRouter(
  import.meta.glob('./routes/**/*.sprig'),
  undefined,
  { mode: 'history' },
);

For this example, place pages under src/app/routes/:

text
routes/
├── index.sprig       # /
├── guide.sprig       # /guide
└── ideas/
    ├── [id].sprig    # /ideas/:id
    └── layout.sprig  # wraps pages in this directory

index.sprig maps to /; [id].sprig matches one path segment and makes the decoded value available as params.id. Catch-all segments are not supported. A layout.sprig wraps descendant pages (a root layout wraps all routes) and receives children; render it with <outlet :view="children" />.

By default, the router uses hash navigation. Pass { mode: 'history' } to use the pathname and History API. Lazy glob loaders load the matched page and its layouts on demand, show loading/error content, and cache successful imports. Manual route maps and eager glob modules are also supported.

Manual routes ​

For explicit route maps, use createRouter(routes, fallback, options). The router exposes current, view(), and navigate(path):

js
import { createRouter } from 'sprig-framework/router';

const router = createRouter({
  '/': HomePage,
  '/guide': GuidePage,
}, NotFoundPage);

router.navigate('/guide');

In history mode, ordinary same-origin links are intercepted; external links, modified clicks, downloads, new-window links, and same-page anchors are left to the browser.

Hosting history routes ​

With history mode, production hosting must serve the app's index.html for unknown page paths. Without that fallback, a direct visit or refresh of /guide may return a server 404 before the client router starts. Vite's development and preview servers provide SPA fallback. Hash mode does not require path-based server fallback.