@molecule/app-routing-sveltekit
Provider bond · routing · App (browser) · v3.0.1 · Apache-2.0
SvelteKit client router provider for @molecule/app-routing
npm install @molecule/app-routing-sveltekitnpm · Source on GitHub · Implements @molecule/app-routing
How it works
@molecule/app-routing-sveltekit is a provider bond on the app (browser) side: it implements the routing core interface (@molecule/app-routing) with a concrete vendor or library behind it.
Your code calls the core; you wire this provider once at startup. Swapping vendors later is one line in that wiring, not a rewrite.
<!-- src/routes/+layout.svelte -->
<script lang="ts">
import { goto } from '$app/navigation'
import { resolve } from '$app/paths'
import { navigating, page } from '$app/state'
import {
createSvelteKitNavigation,
MoleculeRouterProvider,
} from '@molecule/app-routing-sveltekit'
// Build the navigation here, in the root layout's initialisation, once: it watches kit's
// `page` from there. `resolve('/')` gives the bond the base path (or `#` under hash
// routing) kit's `goto` and links need.
const navigation = createSvelteKitNavigation({ goto, page, navigating, rootHref: resolve('/') })
</script>
<MoleculeRouterProvider {navigation}>
{@render children()}
</MoleculeRouterProvider>Works with: @molecule/app-bond, @molecule/app-i18n, @molecule/app-routing, @molecule/app-svelte
Reference
SvelteKit provider for the molecule Router (@molecule/app-routing).
SvelteKit's client router is reachable only inside a SvelteKit app, through the
virtual modules $app/navigation, $app/state and $app/paths, which a package
cannot import. So the app passes those functions in — a SvelteKitNavigation —
and this bond never imports $app/*.
Mount MoleculeRouterProvider ONCE in the root layout, around the rendered page. It
builds one molecule Router over the app's SvelteKit navigation, calls
@molecule/app-routing's setRouter with it, and supplies it to the components below:
this bond's useMoleculeRouter, useMoleculeQuery, useMoleculeNavigate and
useIsActive, and @molecule/app-svelte's router hooks, guards and layouts. Core
navigate() / getRouter() drive the same router — kit links, goto and the back button
all notify the same subscribers, before kit renders the new page.
With HTTP and auth clients bonded, the router MoleculeRouterProvider builds
replaces the current URL with /login after a credential-free GET receives a 401 and
the session is confirmed signed out, as React's BrowserRouter does. location.state.from
holds the original location. Set signInPath to use a different sign-in route or pass
signInPath={false} to opt out.
Auto-generated, AI-first package reference for the molecule.dev ecosystem. It is written to be read by coding agents as much as by people, and is generated from this package's source — edit
src/index.tsJSDoc, not this file.
Quick Start
<!-- src/routes/+layout.svelte -->
<script lang="ts">
import { goto } from '$app/navigation'
import { resolve } from '$app/paths'
import { navigating, page } from '$app/state'
import {
createSvelteKitNavigation,
MoleculeRouterProvider,
} from '@molecule/app-routing-sveltekit'
// Build the navigation here, in the root layout's initialisation, once: it watches kit's
// `page` from there. `resolve('/')` gives the bond the base path (or `#` under hash
// routing) kit's `goto` and links need.
const navigation = createSvelteKitNavigation({ goto, page, navigating, rootHref: resolve('/') })
</script>
<MoleculeRouterProvider {navigation}>
{@render children()}
</MoleculeRouterProvider>
<!-- src/routes/orders/+page.svelte -->
<script lang="ts">
import {
useIsActive,
useMoleculeNavigate,
useMoleculeQuery,
} from '@molecule/app-routing-sveltekit'
const navigate = useMoleculeNavigate()
const query = useMoleculeQuery()
const isOpenActive = useIsActive('/orders', false)
</script>
<p>Page: {$query.page}</p>
<button onclick={() => navigate('/orders', { replace: true })}>Reset</button>
<a href="/orders" class={$isOpenActive ? 'active' : ''}>All orders</a>
Type
provider
Installation
npm install @molecule/app-routing-sveltekit @molecule/app-bond @molecule/app-i18n @molecule/app-routing @molecule/app-svelte @sveltejs/kit svelte
API
Interfaces
ListRouteNavItem
A named list view and its navigation label.
interface ListRouteNavItem extends ListRouteSelection {
/**
* Translated label: the text itself, or a snippet when it includes an icon (React's
* `ReactNode`).
*/
label: string | Snippet
/** Path parameters for this destination; current route parameters are otherwise retained. */
params?: RouteParams
/** Keep the choice visible but prevent navigation. Authorization still belongs in the route. */
disabled?: boolean
}
ListRouteNavItemState
URL-derived state available to the app's link styling.
interface ListRouteNavItemState<Selection extends string = string> {
/** The app-owned selection key. */
selection: Selection
/** Whether the current URL selects this view. */
active: boolean
/** Whether navigation is disabled for this choice. */
disabled: boolean
}
ListRouteNavProps
Props for URL-backed list navigation; local content panels use the UI package's Tabs
instead. It carries every native <nav> attribute React's prop type does (id, class,
data and ARIA attributes, event handlers), so one declaration serves both bonds.
interface ListRouteNavProps<Selection extends string = string> extends Omit<
SvelteHTMLElements['nav'],
'children'
> {
/** Accessible navigation name, translated by the app. */
'aria-label': string
/** Every declared view stays visible on every route; labels and targets share one declaration. */
selections: Record<Selection, ListRouteNavItem>
/** Tie-breaker or fallback, with the same meaning as useListRoute's defaultSelection. */
defaultSelection?: NoInfer<Selection>
/** Pagination query key to remove on selection, defaulting to page. */
pageParam?: string
/** Required for protected selections, with the same readiness rules as useListRoute. */
auth?: ListRouteAuth
/** Render links in a list, with optional classes for the list and its items. */
list?: { className?: string; itemClassName?: string }
/** App-owned styling, resolved from its class map. */
linkClassName?: string | ((state: ListRouteNavItemState<Selection>) => string | undefined)
/**
* Render the list beside the nav using its exact URL state, including resolved item
* params (React's `children`): a snippet receiving the route the nav resolved.
*/
children?: Snippet<[ListRouteResult<string, Selection>]>
}
MoleculeRouterProviderProps
Props for MoleculeRouterProvider: React's routes, onRouterReady and
children, plus the SvelteKit navigation the app builds in its root layout.
interface MoleculeRouterProviderProps {
/**
* The app's SvelteKit pieces, built once in the root layout with
* `createSvelteKitNavigation`: kit's `goto`, `page`, `navigating` and its root href.
*/
navigation: SvelteKitNavigation
/**
* Route definitions for molecule named routes, exactly as the core
* `createHistoryRouter` takes them. Pass a stable array: the router is created with the
* first one, and a later, different array registers onto the same router.
*/
routes?: RouteDefinition[]
/**
* Path to replace the current location with on a signed-out GET 401. Defaults to
* `/login`; `false` turns the redirect off.
*/
signInPath?: string | false
/**
* Called ONCE with the router, during the provider's initialisation and after the bond
* exists, so `@molecule/app-routing`'s `getRouter()` already returns it. Changing the
* callback later does not call it again, as React's provider does not: the router is
* built once for the provider's whole mounted life.
*
* @param router - The router the provider built and bonded.
*/
onRouterReady?: (router: Router) => void
/**
* The page below the provider. Every component rendered here reads the router through
* the bond's hooks.
*/
children: Snippet
}
KitGotoOptions
The subset of SvelteKit's GotoOptions this bond passes (@sveltejs/kit
types/index.d.ts: "export function goto(url: string | URL, opts?: GotoOptions):
Promise<void>"; the bond only ever drives replace, state and persistState).
interface KitGotoOptions {
/**
* "If `true`, replaces the current history entry rather than creating a new one"
* (kit's `GotoOptions.replace`).
*/
replace?: boolean
/**
* "An optional object that will be available as `page.state`" (kit's
* `GotoOptions.state`, typed `App.PageState`).
*/
state?: KitPageState
/**
* "If `true`, `page.state` will be restored after a full page reload" (kit's
* `GotoOptions.persistState`).
*/
persistState?: boolean
}
KitUrl
The parts of the page URL this bond reads. Kit's page.url is read-only (@sveltejs/kit
types/index.d.ts: "export type ReadonlyURL = Readonly<Omit<URL, 'searchParams'> & {
searchParams: ReadonlyURLSearchParams }>"), so the bond asks for no more than it reads;
a URL fits as well.
interface KitUrl {
/** The URL's path, with kit's base path when the app has one. */
readonly pathname: string
/** The URL's query string, `?` included (or `''`). */
readonly search: string
/** The URL's fragment, `#` included (or `''`); the in-app path under hash routing. */
readonly hash: string
}
KitPage
The parts of SvelteKit's Page (@sveltejs/kit types/index.d.ts: "export interface
Page<…> { url: ReadonlyURL & …; params: Params; route: { id: RouteId }; status: number;
error; data; state: App.PageState; form }") this bond reads: the URL for the location,
the params of the route kit matched, and the state carried by the navigation.
interface KitPage {
/**
* "The URL of the current page" (kit's `Page.url`).
*/
url: KitUrl
/**
* "The parameters of the current page - e.g. for a route like `/blog/[slug]`, a
* `{ slug: string }` object" (kit's `Page.params`).
*/
params: Record<string, string>
/**
* "The page state, which can be manipulated using the `pushState` and `replaceState`
* functions from `$app/navigation`" (kit's `Page.state`, typed `App.PageState`).
*/
state: KitPageState
}
KitPageChange
What a KitNavigateListener hears each time kit's page moves to a new URL or a new
page.state: the kind of navigation kit was making then.
interface KitPageChange {
/**
* Kit's navigation kind (`$app/state`'s `navigating.type`), or `null` when kit changed its
* page outside a navigation: following a link to a hash on the same page, `pushState` or
* `replaceState` from `$app/navigation`, or a back/forward move between such entries.
*/
type: KitNavigationType | null
}
KitNavigating
The part of kit's navigating ($app/state) this bond reads (@sveltejs/kit
types/index.d.ts: "A read-only object representing an in-progress navigation, with
from, to, type and (if type === 'popstate') delta properties. Values are null
when no navigation is occurring").
interface KitNavigating {
/** The kind of the navigation in flight, or `null` when none is. */
readonly type: KitNavigationType | null
}
SvelteKitNavigation
The subset of SvelteKit's client router this bond drives — what an app builds from
$app/navigation, $app/state and $app/paths in its root layout and passes to
createSvelteKitRouter. goto and page are kit's own exports and rootHref is
kit's resolve('/'); onNavigate tells the router when kit's page changed.
createSvelteKitNavigation builds all four from kit's exports.
interface SvelteKitNavigation {
/**
* SvelteKit's programmatic navigation (`$app/navigation`'s `goto`, `@sveltejs/kit`
* `types/index.d.ts`: "Allows you to navigate programmatically to a given route …
* Returns a Promise that resolves when SvelteKit navigates (or fails to navigate, in
* which case the promise rejects) to the specified `url`.").
*
* @param url - The URL to navigate to, with the app's base (or `#`) first.
* @param opts - `replace`, `state` and `persistState`; the bond passes nothing else.
* @returns Kit's navigation promise.
*/
goto(url: string, opts?: KitGotoOptions): Promise<void>
/**
* Kit's `page` — `$app/state`'s `page` (`@sveltejs/kit` `types/index.d.ts`: "A read-only
* reactive object with information about the current page … In the browser, the values
* can be read at any time"). Read at call time for the current location and params.
*/
page: KitPage
/**
* The href of the app's root, kit's `resolve('/')` from `$app/paths`: `'/'`,
* `'/app/'` under `paths.base: '/app'`, or `'#/'` under `router: { type: 'hash' }`
* (`resolve` "prefix[es] it with the base path, if any … In hash routing mode, the
* returned URL starts with `#`"). Kit's `goto` does not add the base itself ("if you've
* set `config.paths.base` and the URL is root-relative, you need to prepend the base
* path"), so the bond puts this prefix before every path it navigates to or links.
*/
rootHref: string
/**
* Calls `listener` each time kit's `page` moves to a new URL or a new `page.state`, before
* kit renders the page for it. `createSvelteKitNavigation` watches kit's `page` once and
* passes each change to every listener, so the router can listen and stop listening
* repeatedly.
*
* @param listener - Called once per change of kit's page.
* @returns A function that stops the listener.
*/
onNavigate(listener: KitNavigateListener): () => void
}
SvelteKitExports
Kit's own exports that createSvelteKitNavigation turns into a
SvelteKitNavigation: goto from $app/navigation, page and navigating from
$app/state, and rootHref from $app/paths' resolve('/').
interface SvelteKitExports extends Pick<SvelteKitNavigation, 'goto' | 'page' | 'rootHref'> {
/**
* Kit's `navigating` (`$app/state`). Read when kit's `page` changes, so a back or forward
* move is heard as a pop.
*/
navigating: KitNavigating
}
SvelteKitRouterOptions
Options for createSvelteKitRouter.
interface SvelteKitRouterOptions {
/**
* Route definitions for named routes and route params, exactly as the core
* `createHistoryRouter` takes them.
*/
routes?: RouteDefinition[]
/**
* Called once, with the router just built, the way React's `MoleculeRouterProvider` calls
* `onRouterReady` once when it mounts. An app whose layout needs the router elsewhere (to
* hand it to `setMoleculeContext` or `setRouter`, or to read a guard) gets it here instead of
* building a second router for it.
*
* @param router - The router `createSvelteKitRouter` built.
*/
onRouterReady?: (router: Router) => void
/**
* Path to replace the current location with on a signed-out GET 401. Defaults to
* `/login`; `false` turns the redirect off.
*/
signInPath?: string | false
}
UseListRouteResult
What useListRoute returns: each list field as a readable store, the actions as plain functions.
interface UseListRouteResult<Filter extends string = string, Selection extends string = string> {
/** The current 1-indexed page. */
page: Readable<number>
/** The configured items per page. */
pageSize: Readable<number>
/** The zero-indexed item offset for an API request. */
offset: Readable<number>
/** The current URL filter values, including values supplied by path parameters. */
filters: Readable<Record<Filter, string | undefined>>
/** The matching view, or the configured fallback. */
selection: Readable<Selection | undefined>
/** The decoded current path parameters, also usable as API-only filters. */
params: Readable<RouteParams>
/** False while a protected selection is awaiting auth, signed out, or unavailable. */
canLoad: Readable<boolean>
/** Readiness for the current view; a public view always stays ready. */
status: Readable<ListRouteResult<Filter, Selection>['status']>
/** The sign-in destination while a signed-out protected view is being redirected. */
redirectTo: Readable<string | undefined>
/** Builds a real link target, preserving the pathname, unrelated query values and hash. */
href: ListRouteResult<Filter, Selection>['href']
/** Navigates atomically; location state is preserved unless options replace it. */
navigate: ListRouteResult<Filter, Selection>['navigate']
/** Changes only the page, retaining the current filters and view. */
setPage: ListRouteResult<Filter, Selection>['setPage']
/** Patches URL filters and returns to page one. */
setFilters: ListRouteResult<Filter, Selection>['setFilters']
/** Selects a configured view at page one. */
select: ListRouteResult<Filter, Selection>['select']
}
ListRouteFilter
Where a list filter lives in the URL. Path values take precedence over query values.
interface ListRouteFilter {
/** Query key; defaults to the filter's name when `param` is absent. */
query?: string
/** Path parameter supplied by the current route, such as `category` in `/topics/:category`. */
param?: string
/** Value returned when neither URL source supplies a value; omitted from generated queries. */
defaultValue?: string
}
ListRouteSelection
A selectable list view, expressed in the app's own route contract.
interface ListRouteSelection {
/** Absolute route pattern, for example `/members/:member/saved`. */
path: string
/** Query values identifying this view. An undefined value requires the key to be absent. */
query?: QueryParams
/** A protected selection never loads before authentication is confirmed. */
requiresAuth?: boolean
}
ListRouteAuth
Authentication readiness for protected list selections.
interface ListRouteAuth {
/** The auth client's status. Unavailable is distinct from a signed-out session. */
status: 'loading' | 'authenticated' | 'unauthenticated' | 'unavailable'
/** App-owned sign-in URL. A signed-out protected visit replaces history with this URL. */
redirectTo: string
}
ListRouteOptions
URL-backed list state configuration; it neither invents nor rewrites the app's route contract.
interface ListRouteOptions<Filter extends string = string, Selection extends string = string> {
/** Fixed number of items per page; defaults to 20. */
pageSize?: number
/** Query key for a 1-indexed page; defaults to `page`. Page one omits the key. */
pageParam?: string
/** Route pattern for changing path-backed filters when no selections are configured. */
path?: string
/** Filters and their URL sources. API-only filters do not belong here. */
filters?: Record<Filter, ListRouteFilter>
/** Named views sharing a list. Both path variants and query variants are supported. */
selections?: Record<Selection, ListRouteSelection>
/** Tie-breaker when multiple selections match, or fallback when none matches. */
defaultSelection?: NoInfer<Selection>
/** Required when a selection is protected. Public views remain public as auth changes. */
auth?: ListRouteAuth
}
ListRouteChange
A single atomic list navigation. Filter/selection changes reset page unless explicitly supplied.
interface ListRouteChange<Filter extends string = string, Selection extends string = string> {
/** Target page, starting at one. */
page?: number
/** Patch of URL filter values. Undefined removes a query filter. */
filters?: Partial<Record<Filter, string | undefined>>
/** Target view, resolved through its configured path and query values. */
selection?: Selection
/** Optional path parameter changes, for example when opening a different member's saved view. */
params?: RouteParams
}
ListRouteResult
List state and navigation, derived directly from the current location.
interface ListRouteResult<Filter extends string = string, Selection extends string = string> {
/** Current 1-indexed page; malformed and non-positive URL values read as page one. */
page: number
/** Configured items per page. */
pageSize: number
/** Zero-indexed item offset for an API request. */
offset: number
/** Current URL filter values, including values supplied by path parameters. */
filters: Record<Filter, string | undefined>
/** Matching view, or the configured fallback. */
selection: Selection | undefined
/** Decoded current path parameters, also usable as API-only filters. */
params: RouteParams
/** False while a protected selection is awaiting auth, signed out, or unavailable. */
canLoad: boolean
/** Readiness for the current view. A public view always stays ready. */
status: 'ready' | 'loading' | 'unauthenticated' | 'unavailable'
/** Sign-in destination while a signed-out protected view is being redirected. */
redirectTo: string | undefined
/** Build a real link target, preserving the current pathname, unrelated query values and hash. */
href: (change?: ListRouteChange<Filter, Selection>) => string
/** Navigate atomically. Location state is preserved unless options explicitly replace it. */
navigate: (change: ListRouteChange<Filter, Selection>, options?: NavigateOptions) => void
/** Change only the page, retaining the current filters and view. */
setPage: (page: number, options?: NavigateOptions) => void
/** Patch URL filters and return to page one. */
setFilters: (
filters: Partial<Record<Filter, string | undefined>>,
options?: NavigateOptions,
) => void
/** Select a configured view at page one, preserving current route parameters. */
select: (selection: Selection, options?: NavigateOptions) => void
}
RouteLocation
Current URL decomposed into pathname, search string, hash, navigation state, and unique key.
interface RouteLocation {
/**
* Current pathname.
*/
pathname: string
/**
* Query string (including leading ?).
*/
search: string
/**
* Hash (including leading #).
*/
hash: string
/**
* State data passed with navigation.
*/
state?: unknown
/**
* Unique key for this location.
*/
key?: string
}
RouteMatch
Result of matching a URL against a route pattern (path, params, query string).
interface RouteMatch<Params extends RouteParams = RouteParams> {
/**
* Route path pattern.
*/
path: string
/**
* Matched URL pathname.
*/
pathname: string
/**
* Route parameters.
*/
params: Params
/**
* Whether this is an exact match.
*/
isExact: boolean
}
NavigateOptions
Options for programmatic navigation (replace vs push, carry state, preserve query/hash).
interface NavigateOptions {
/**
* Replace current history entry instead of pushing.
*/
replace?: boolean
/**
* State to pass with navigation.
*/
state?: unknown
/**
* Preserve current query params.
*/
preserveQuery?: boolean
/**
* Preserve current hash.
*/
preserveHash?: boolean
}
RouteDefinition
Route configuration entry (path pattern, name, auth requirements, roles, children).
interface RouteDefinition {
/**
* Route path pattern.
*/
path: string
/**
* Route name (for named routes).
*/
name?: string
/**
* Whether the route requires exact matching.
*/
exact?: boolean
/**
* Whether the route requires authentication.
*/
requiresAuth?: boolean
/**
* Required roles/permissions.
*/
roles?: string[]
/**
* Route metadata.
*/
meta?: Record<string, unknown>
/**
* Child routes.
*/
children?: RouteDefinition[]
}
Router
Client-side router providing navigation, guards, route matching, and history control.
All routing providers must implement this interface.
interface Router {
/**
* Returns the current route location (pathname, search, hash, state).
*/
getLocation(): RouteLocation
/**
* Gets the current route params.
*/
getParams<T extends RouteParams = RouteParams>(): T
/**
* Gets the current query params.
*/
getQuery(): QueryParams
/**
* Gets a specific query parameter.
*/
getQueryParam(key: string): string | undefined
/**
* Gets the current hash.
*/
getHash(): string
/**
* Navigates to a path. A path that is only a query or a hash (`'?tab=2'`, `'#top'`) stays on
* the current page, as React Router's `navigate` does; a hash alone drops the current query.
*/
navigate(path: string, options?: NavigateOptions): void
/**
* Navigates to a named route.
*/
navigateTo(
name: string,
params?: RouteParams,
query?: QueryParams,
options?: NavigateOptions,
): void
/**
* Goes back in history.
*/
back(): void
/**
* Goes forward in history.
*/
forward(): void
/**
* Goes to a specific point in history.
*/
go(delta: number): void
/**
* Updates the current query params.
*/
setQuery(params: QueryParams, options?: NavigateOptions): void
/**
* Updates a specific query parameter.
*/
setQueryParam(key: string, value: string | undefined, options?: NavigateOptions): void
/**
* Updates the current hash.
*/
setHash(hash: string, options?: NavigateOptions): void
/**
* Checks if a path matches the current location.
*
* @returns `true` if the path matches the current route.
*/
isActive(path: string, exact?: boolean): boolean
/**
* Matches a path pattern against a pathname.
*/
matchPath<Params extends RouteParams = RouteParams>(
pattern: string,
pathname: string,
): RouteMatch<Params> | null
/**
* Generates a URL from a named route.
*/
generatePath(name: string, params?: RouteParams, query?: QueryParams): string
/**
* The `href` an anchor to the in-app `path` carries, as the native router's own link
* writes it (its base path prefixed, or `#/…` under a hash history), so a middle-click,
* a new tab or a copied link opens the same page a click does. A `path` that is only a
* query or a hash (`'?tab=2'`, `'#top'`) is the current page's, as `navigate` reads it
* and as React Router's `<Link>` writes it: `'#top'` on `/docs?x=1` is `/docs#top`.
*
* @param path - Pathname with optional query string and hash, as passed to `navigate`.
* @returns The `href`.
*/
createHref(path: string): string
/**
* Calls `listener` once after each navigation the router commits, however it started (a
* link, the back button, `navigate`), with the new location and the navigation action.
* A router calls it before the browser paints the new page, so a component that renders
* from a listener (the framework bindings' `useLocation` and `useParams` do) shows the new
* location in the same paint as the new page. Molecule's router conformance tests check
* that at every paint.
*
* @param listener - Called with the new location and the navigation action.
* @returns Stops calling `listener`.
*/
subscribe(listener: RouteChangeListener): () => void
/**
* Adds a navigation guard.
*/
addGuard(guard: NavigationGuard): () => void
/**
* Registers route definitions.
*/
registerRoutes(routes: RouteDefinition[]): void
/**
* Gets all registered routes.
*/
getRoutes(): RouteDefinition[]
/**
* Destroys the router.
*/
destroy(): void
}
RouterConfig (deprecated)
Deprecated: Use
BrowserRouterConfig(createBrowserRouter) orMemoryRouterConfig(createMemoryRouter): each takes only the options it acts on.
Configuration options for creating a router instance.
interface RouterConfig {
/**
* Router mode.
*/
mode?: 'history' | 'hash' | 'memory'
/**
* Base path.
*/
basePath?: string
/**
* Initial routes.
*/
routes?: RouteDefinition[]
}
Types
KitPageState
The state object SvelteKit keeps in a history entry and exposes as page.state.
Mirrors kit's App.PageState — @sveltejs/kit types/index.d.ts: "export interface
PageState {}", an empty interface apps extend — so it is typed as object: every
object an app declares for App.PageState is assignable, and nothing else is assumed
about its shape. Kit stores it inside the history entry, in the state of the
sveltekit:metadata record (src/runtime/client/client.js), which is why it must be
an object.
type KitPageState = object
KitNavigationType
SvelteKit's navigation kinds (@sveltejs/kit types/index.d.ts: "export type
NavigationType = 'enter' | 'form' | 'leave' | 'link' | 'goto' | 'popstate'").
type KitNavigationType = 'enter' | 'form' | 'leave' | 'link' | 'goto' | 'popstate'
KitNavigateListener
A listener the SvelteKitNavigation.onNavigate adapter calls each time kit's page
moves to a new URL or a new page.state, before kit renders the page for it.
type KitNavigateListener = (change: KitPageChange) => void
UseConsumedSearchParamStore
The store useConsumedSearchParam returns: the current [value, set] tuple.
type UseConsumedSearchParamStore = Readable<readonly [string, (value: string) => void]>
RouteParams
URL path parameter key-value map extracted from dynamic route segments (e.g. { id: '123' }).
type RouteParams = Record<string, string>
QueryParams
URL query string parameter map (single values or arrays for repeated keys).
type QueryParams = Record<string, string | string[] | undefined>
GuardResult
Navigation guard result.
type GuardResult = boolean | string | { path: string; replace?: boolean } | void
NavigationGuard
Navigation guard function invoked before each navigation.
Return false to cancel, a string/path to redirect, or void to allow.
type NavigationGuard = (
to: RouteLocation,
from: RouteLocation | null,
) => GuardResult | Promise<GuardResult>
to— The target route location being navigated to.from— The current route location being navigated away from, ornullon initial load.
RouteChangeListener
Callback invoked on each route change with the new location and the navigation action that triggered it.
type RouteChangeListener = (location: RouteLocation, action: NavigationAction) => void
Functions
createSvelteKitNavigation(kit)
Builds the SvelteKitNavigation that createSvelteKitRouter takes, from kit's own
exports. Call it during the root layout's component initialisation (Svelte creates the
effect it uses only then, and throws effect_orphan anywhere else).
It watches kit's page once, with a pre-effect, and passes each move to a new URL or a new
page.state to every listener the router adds. Svelte runs a component's pre-effects
before the components below it update, so the router's subscribers (the binding's stores,
a layout's active item) read the new location in the same update that renders the new
page: no component shows the previous location beside it. A navigation kit cancelled never
changes page, so it is never heard, and an invalidation that keeps the URL and the state
is not heard either.
function createSvelteKitNavigation(kit: SvelteKitExports): SvelteKitNavigation
kit— Kit'sgoto,page,navigatingandresolve('/').
Returns: The navigation pieces for createSvelteKitRouter.
createSvelteKitRouter(kit, options)
Builds the molecule Router over a SvelteKit app's client router.
The app passes the SvelteKitNavigation createSvelteKitNavigation built from kit's
goto, page, navigating and root href, once, from the root layout. MoleculeRouterProvider builds it there and bonds it with
@molecule/app-routing's setRouter; a layout that builds it by hand does the same, and
may also supply it to @molecule/app-svelte's setMoleculeContext.
Subscribers hear one call each time kit's page moves to a new URL or a new page.state,
before kit renders the page for it: kit links, the back button, goto, this router's own
navigate, and the changes kit makes outside a navigation (a link to a hash on the same
page, shallow routing). A navigation kit's own guards cancelled never changes page, so it
never notifies. The action is 'pop' for kit's back/forward navigations and the one this
router started for its own; anything else is heard as a 'push', because kit does not say
whether a change it made replaced the current entry (goto(url, { replaceState: true })
from app code, shallow replaceState) or moved between shallow entries. The history holds
no resources of its own: the subscription is released through the unsubscribe listen
returns.
function createSvelteKitRouter(kit: SvelteKitNavigation, options?: SvelteKitRouterOptions): Router
kit— The SvelteKit pieces (seeSvelteKitNavigation).options— Route definitions, an optionalonRouterReadycalled once with the router, and thesignInPatha signed-out GET 401 sends the visitor to (falseturns it off).
Returns: The router.
useConsumedSearchParam(name)
Takes a one-time credential (a reset token, an OAuth code) out of the URL and keeps
it in memory, React's useConsumedSearchParam in Svelte's idiom: a readable store of
the [value, set] tuple, through the router the nearest MoleculeRouterProvider built
over the app's SvelteKit navigation. The parameter is removed with a replace navigation
that keeps the path, the hash, the other query values and the location state; the value
survives renders and later query-only navigation, Back to an entry restores the value
consumed there, and a new value arriving on the same mounted route is consumed too.
Call it during a component's initialisation, where Svelte reads context. It connects on mount, as React's effect does, so a server render never navigates.
function useConsumedSearchParam(name: string): UseConsumedSearchParamStore
name— The query key to consume, for exampletokenorcode.
Returns: A readable store of the consumed value ('' before the parameter was ever present) and a setter (a form clears it after a successful submit).
useIsActive(path, exact)
Whether path is the current location (or a prefix of it), React's useIsActive() in
@molecule/app-svelte's shape: a readable store that re-evaluates after every
navigation the router commits, so a nav link reading $isActive updates on a link
click, a back button or a navigation made here.
Call it during a component's initialisation, where Svelte reads context.
function useIsActive(path: string, exact?: boolean): Readable<boolean>
path— The path to check.exact— Whether to require an exact match (default: a prefix match).
Returns: A readable store of whether the path is active.
useListRoute(options)
URL-backed pagination, filters and selected views, React's useListRoute in Svelte's
idiom: the page, the filters and the view live in the URL only, so a reload, a shared
link and Back all show the same list. Each list field is a readable store that follows
the location, and the actions are plain functions, through the router the nearest
MoleculeRouterProvider built over the app's SvelteKit navigation. Built on
resolveListRoute from @molecule/app-routing, so every framework binding returns the
same result.
A signed-out visit to a view with requiresAuth replaces the entry with
options.auth.redirectTo, carrying state.returnTo; until auth is confirmed canLoad
is false.
The options may be a plain value or a readable store of one (a store holding
undefined means the default options): an auth status moving from loading to
unauthenticated re-resolves the list — and performs the sign-in redirect — on the
same component, the way React re-renders useListRoute.
Call it during a component's initialisation, where Svelte reads context.
function useListRoute<Filter extends string = string, Selection extends string = string>(
options?: MaybeReadable<ListRouteOptions<Filter, Selection> | undefined>,
): UseListRouteResult<Filter, Selection>
options— Filter sources, view paths, pagination and optional auth readiness (or a store of them).
Returns: Each list field as a readable store, and its link builder and navigation actions.
useMoleculeNavigate()
A navigate function backed by the provider's molecule Router, React's
useMoleculeNavigate() in Svelte's idiom. It takes molecule's own NavigateOptions
(replace, state, preserveQuery, preserveHash) and drives SvelteKit's client
router through the bond.
Call it during a component's initialisation, where Svelte reads context.
function useMoleculeNavigate(): Router['navigate']
Returns: A function that navigates to a path.
useMoleculeQuery(T)
The current query params as a readable store, React's useMoleculeQuery() in
@molecule/app-svelte's shape: the store re-emits after every navigation the router
commits, so a component reading $query re-renders on a link click, a back button or a
navigation made here.
Call it during a component's initialisation, where Svelte reads context.
function useMoleculeQuery<T extends QueryParams = QueryParams>(): Readable<T>
T— The query record type.
Returns: A readable store of the current query parameters.
useMoleculeRouter()
The molecule Router the nearest MoleculeRouterProvider built over the app's
SvelteKit navigation. React's useMoleculeRouter() with no per-component fallback:
SvelteKit's client router is reachable only through the app's $app/* modules, so the
bond cannot build one here — without a provider there is no router to return.
Call it during a component's initialisation, where Svelte reads context; the returned router is the same object for the provider's whole mounted life.
function useMoleculeRouter(): Router
Returns: The provider's router.
parseSearchParams(searchParams)
Converts URLSearchParams into QueryParams. A key that appears more than once becomes an array
of its values, in order.
function parseSearchParams(searchParams: URLSearchParams): QueryParams
searchParams— The search params to read.
Returns: The query params.
stringifyQuery(params)
Serializes QueryParams into a query string with a leading ?, percent-encoding keys and values
(a space is %20). Undefined values are left out; an array writes its key once per value.
function stringifyQuery(params: QueryParams): string
params— The query params.
Returns: The query string, or '' when there is nothing to write.
matchPath(pattern, pathname, exact)
Matches a route pattern against a pathname. :name captures one segment and * matches
anything. The whole pathname must match unless exact is false, which also accepts a pathname
that only starts with the pattern.
function matchPath<Params extends RouteParams = RouteParams>(
pattern: string,
pathname: string,
exact?: boolean,
): RouteMatch<Params> | null
pattern— The pattern, such as/users/:idor/files/*.pathname— The pathname to match.exact— Whether the whole pathname must match (defaulttrue).
Returns: The match with its params, or null.
generatePath(pattern, params)
Builds a path from a pattern by putting each :name param in its place, percent-encoded. A
pattern given no params is returned as it is.
function generatePath(pattern: string, params?: RouteParams): string
pattern— The pattern, such as/users/:id.params— The param values.
Returns: The path.
resolvePath(to, fromPathname)
Resolves a path against the pathname it is relative to: an absolute to is returned as it is;
otherwise to is joined to fromPathname's parent, with .. moving up and . staying.
function resolvePath(to: string, fromPathname: string): string
to— The path to resolve.fromPathname— The pathname it is relative to.
Returns: The resolved pathname.
normalizePath(path)
Removes trailing slashes from a path, keeping / itself.
function normalizePath(path: string): string
path— The path.
Returns: The path without trailing slashes.
Constants
MoleculeRouterProvider
const MoleculeRouterProvider: LegacyComponentType
ListRouteNav
const ListRouteNav: LegacyComponentType
provider
The conventional typed provider constant: the core's browser-history router
(createBrowserRouter), for molecule code running OUTSIDE a SvelteKit app — tests,
stories, or a plain page that mounts molecule components. Inside a SvelteKit app do
not use it: it would read window.location and push window.history behind kit's
back. Create the real router with createSvelteKitRouter from the root layout.
const provider: Router
Core Interface
Implements @molecule/app-routing interface.
Bond Wiring
Setup function to register this provider with the core interface:
import { setRouter } from '@molecule/app-routing'
import { provider } from '@molecule/app-routing-sveltekit'
export function setupRoutingSveltekit(): void {
setRouter(provider)
}
Injection Notes
Requirements
Peer dependencies:
@molecule/app-bond^1.0.1@molecule/app-i18n^1.0.1@molecule/app-routing^1.5.0@molecule/app-svelte^3.10.0 || ^4.0.0@sveltejs/kit^3.0.0svelte^5.7.0
Runtime Dependencies
-
@molecule/app-bond -
@molecule/app-i18n -
@molecule/app-routing -
@molecule/app-svelte -
@sveltejs/kit -
svelte -
The provider calls
setRouter. On initialisation it bonds the router it built, so other molecule packages'navigate()/getRouter()drive SvelteKit's client router instead of pushingwindow.historybehind kit's back.onRouterReadyreceives that router once, after the bond exists; changing the callback later does not call it again. -
Kit 3. The bond drives kit 3's
gotooptions (replace,persistState) and$app/state'spage; a kit 2 app uses@molecule/app-routing-sveltekit1.x. -
Read the location through the router, not
page. Molecule packages seegetLocation()/subscribe(), with paths inside the app (no base, no#);router.createHref(path)is the href kit's links carry. -
The exported
providerconstant is NOT for SvelteKit apps — it is the core browser-history router, for molecule code outside SvelteKit. Wiring it in a SvelteKit app moves history behind kit's back. -
The hooks are component-initialisation hooks, as React's are render hooks: Svelte reads context then, so call them in a component's
<script>, never in a module, an event handler or an async callback. -
SvelteKit gives a layout its page as
children. The bond provides no routed view, so@molecule/app-svelte'sRoutedViewthrows and says to render{@render children()}. -
A change kit makes outside a navigation is heard as a push. Following a link to a hash on the same page, shallow routing's
pushState/replaceState, or a back/forward move between such entries changes kit'spagewith no navigation kind, and kit does not say whether agoto(url, { replaceState: true })from app code replaced the entry; this router's ownnavigateand kit's back/forward navigations carry their real action. -
Navigation state is
page.state, so it must be an object; kit's ownsveltekit:*history keys are stripped fromgetLocation().state.