TheDocumentation 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.
listen function lets you register a callback that fires whenever the current route changes, whether that change came from a navigate() call, a <Link> click, or the browser’s back/forward buttons. It is designed for use outside of Svelte components — for example in plain TypeScript modules, analytics helpers, or application bootstrap code. Inside Svelte components you should prefer the useLocation, useRouter, or useHistory hooks, which integrate cleanly with Svelte’s reactivity system and automatically clean up when the component is destroyed.
Import
Signature
Parameters
A callback invoked on every route change. Receives a single event object with three properties:
location— A snapshot of the currentwindow.locationextended withstate(fromwindow.history.state) andkey(a timestamp string). Includes the standardpathname,search,hash,href, andoriginproperties.action— Either"PUSH"(navigate/Link triggered) or"POP"(browser back/forward button). See action values below.preserveScroll— Forwarded from the originatingnavigate()call.undefinedon"POP"actions.
Return value
A zero-argument function that removes the listener and cleans up the underlying
popstate event handler. Always call this when the listener is no longer needed to prevent memory leaks.Action values
| Value | Triggered by | Notes |
|---|---|---|
"PUSH" | navigate(), <Link> clicks, use:link, use:links | A new entry was added to (or replaced in) the history stack |
"POP" | Browser back / forward buttons, history.go() | The user moved within the existing history stack |
"PUSH" is emitted for both pushState and replaceState operations. There is no separate "REPLACE" action — if you need to distinguish them, check whether the location.key has changed between events.Examples
Inside vs. outside components
| Context | Recommended API | Reason |
|---|---|---|
| Outside Svelte components | listen() | No Svelte context available; manage lifecycle manually |
| Inside Svelte components | useLocation(), useRouter(), useHistory() | Hooks integrate with Svelte’s $state / $derived reactivity and auto-cleanup on destroy |