Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/jpcutshall/svelte5-router/llms.txt

Use this file to discover all available pages before exploring further.

useRouter() returns the RouterContext object provided by the nearest ancestor <Router> component. It exposes reactive stores that track which route is currently active, what base path the router is mounted on, and the derived base for child routers. It also provides the registerRoute and unregisterRoute functions that <Route> uses to announce itself to the router—most application code will never need to call these directly. Like all context hooks, useRouter() must be called during Svelte component initialisation.

Signature

import { useRouter } from "svelte5-router";

const router = useRouter();
// router is RouterContext | undefined (undefined when no parent Router exists)
If there is no ancestor <Router> in the component tree, useRouter() returns undefined. Always guard against this when building reusable components that might be rendered outside a <Router>.

Return value

useRouter() returns a RouterContext object (or undefined when called outside a router tree).

RouterContext

activeRoute
Readable<ActiveRoute>
A Svelte readable store that holds information about the route the router has selected as the best match. Updated on every navigation.
base
Readable<{ path: string; uri: string }>
A readable store representing the base that this router was initialised with. For a top-level router this is the basepath prop value (default "/"). For nested routers it inherits from the parent router’s routerBase.
routerBase
Readable<{ path: string; uri: string }>
A derived readable store that reflects the effective base for child routers. It equals base when no route is active; once a route is matched it is derived from that route’s path and URI so that nested <Router> components resolve paths correctly.
registerRoute
(route: Omit<RouteConfig, 'default'>) => void
Registers a route configuration with the parent router so it can be scored and matched against the current location. Called automatically by <Route> on mount.
This function is part of the internal contract between <Route> and <Router>. Calling it directly from application code can corrupt the router’s route list and produce unpredictable matching behaviour.
unregisterRoute
(route: RouteConfig) => void
Removes a previously registered route from the parent router. Called automatically by <Route> on destroy.
Like registerRoute, this is intended for internal use by <Route>. Avoid calling it from application code.

Examples

Reading the active route URI

Use $router.activeRoute to read information about what is currently displayed. This is useful for analytics, breadcrumbs, or conditionally rendering UI based on which route is active.
<script lang="ts">
  import { useRouter } from "svelte5-router";

  const router = useRouter();
</script>

{#if router}
  <p>Active URI: {$router.activeRoute?.uri ?? "none"}</p>
  <p>Base path: {$router.base.path}</p>
{/if}

Reading path parameters from the active route

<script lang="ts">
  import { useRouter } from "svelte5-router";

  const router = useRouter();
  const params = $derived($router?.activeRoute?.params ?? {});
</script>

{#if params.id}
  <p>Viewing item #{params.id}</p>
{/if}

Checking the base path in a nested context

When building reusable widget components that may be placed inside a nested <Router>, you can inspect the current base to construct correct links.
<script lang="ts">
  import { useRouter } from "svelte5-router";

  const router = useRouter();
  const basePath = $derived($router?.base?.path ?? "/");
</script>

<nav>
  <a href="{basePath}/settings">Settings</a>
  <a href="{basePath}/profile">Profile</a>
</nav>

Full example — breadcrumb component

<script lang="ts">
  import { useRouter } from "svelte5-router";

  const router = useRouter();

  const segments = $derived.by(() => {
    const uri = $router?.activeRoute?.uri ?? "/";
    return uri
      .split("/")
      .filter(Boolean)
      .map((seg, i, arr) => ({
        label: seg,
        href: "/" + arr.slice(0, i + 1).join("/"),
      }));
  });
</script>

<nav aria-label="Breadcrumb">
  <ol>
    <li><a href="/">Home</a></li>
    {#each segments as { label, href }}
      <li><a {href}>{label}</a></li>
    {/each}
  </ol>
</nav>

Constraints

useRouter() uses Svelte’s getContext() and must be called during component initialisation, at the top level of a <script> block. Calling it inside a callback, $effect, or outside a .svelte file will not work.
When building reusable components that may be used both inside and outside a <Router>, always check that the returned value is not undefined before accessing its properties.

Build docs developers (and LLMs) love