```js // @noErrors import { afterNavigate, beforeNavigate, disableScrollHandling, goto, invalidate, invalidateAll, onNavigate, preloadCode, preloadData, pushState, refreshAll, replaceState, snapshot } from '$app/navigation'; ``` ## afterNavigate A lifecycle function that runs the supplied `callback` when the current component mounts, and also whenever we navigate to a URL. `afterNavigate` must be called during a component initialization. It remains active as long as the component is mounted.
```dts function afterNavigate( callback: (navigation: AfterNavigate) => void ): void; ```
## beforeNavigate A navigation interceptor that triggers before we navigate to a URL, whether by clicking a link, calling `goto(...)`, or using the browser back/forward controls. Calling `cancel()` will prevent the navigation from completing. If `navigation.type === 'leave'` — meaning the user is navigating away from the app (or closing the tab) — calling `cancel` will trigger the native browser unload confirmation dialog. In this case, the navigation may or may not be cancelled depending on the user's response. When a navigation isn't to a SvelteKit-owned route (and therefore controlled by SvelteKit's client-side router), `navigation.to.route.id` will be `null`. If the navigation will (if not cancelled) cause the document to unload — in other words `'leave'` navigations and `'link'` navigations where `navigation.to.route === null` — `navigation.willUnload` is `true`. `beforeNavigate` must be called during a component initialization. It remains active as long as the component is mounted.
```dts function beforeNavigate( callback: (navigation: BeforeNavigate) => void ): void; ```
## disableScrollHandling If called when the page is being updated following a navigation (in `onMount` or `afterNavigate` or an action, for example), this disables SvelteKit's built-in scroll handling. This is generally discouraged, since it breaks user expectations.
```dts function disableScrollHandling(): void; ```
## goto Allows you to navigate programmatically to a given route, with control over details such as whether scroll and focus are reset (as they would be with a regular navigation) or preserved. Returns a Promise that resolves when SvelteKit navigates (or fails to navigate, in which case the promise rejects) or the state change has been applied. `goto` is intended for navigations to routes that belong to the app, and will reject if a route cannot be resolved. For external URLs, use `window.location = url` to perform a full-page navigation instead of calling `goto(url)`.
```dts function goto( url: string | URL, opts?: GotoOptions ): Promise; ```
## invalidate Causes any `load` functions belonging to the currently active page to re-run if they depend on the `url` in question, via `fetch` or `depends`. Returns a `Promise` that resolves when the page is subsequently updated. If the argument is given as a `string` or `URL`, it must resolve to the same URL that was passed to `fetch` or `depends` (including query parameters). To create a custom identifier, use a string beginning with `[a-z]+:` (e.g. `custom:state`) — this is a valid URL. The `function` argument can be used define a custom predicate. It receives the full `URL` and causes `load` to rerun if `true` is returned. This can be useful if you want to invalidate based on a pattern instead of a exact match. ```ts // Example: Match '/path' regardless of the query parameters import { invalidate } from '$app/navigation'; invalidate((url) => url.pathname === '/path'); ```
```dts function invalidate( resource: string | URL | ((url: URL) => boolean), keepState?: boolean ): Promise; ```
## invalidateAll
Use [`refreshAll`](/docs/kit/$app-navigation#refreshAll) instead. Unlike `invalidateAll`, `refreshAll` does not reset `page.state`.
Causes all `load` and `query` functions belonging to the currently active page to re-run. Returns a `Promise` that resolves when the page is subsequently updated. Note that this resets `page.state` to an empty object. If you want to preserve `page.state` (for example when using [shallow routing](/docs/kit/shallow-routing)), use `refreshAll` instead.
```dts function invalidateAll(): Promise; ```
## onNavigate A lifecycle function that runs the supplied `callback` immediately before we navigate to a new URL except during full-page navigations. If you return a `Promise`, SvelteKit will wait for it to resolve before completing the navigation. This allows you to — for example — use `document.startViewTransition`. Avoid promises that are slow to resolve, since navigation will appear stalled to the user. If a function (or a `Promise` that resolves to a function) is returned from the callback, it will be called once the DOM has updated. `onNavigate` must be called during a component initialization. It remains active as long as the component is mounted.
```dts function onNavigate( callback: ( navigation: OnNavigate ) => MaybePromise<(() => void) | void> ): void; ```
## preloadCode Programmatically imports the code for routes that haven't yet been fetched. Typically, you might call this to speed up subsequent navigation. Takes a route ID such as `/about` or `/blog/[slug]`. Unlike pathnames, route IDs are never prefixed with the app's [base path](/docs/kit/configuration#paths). If you have a pathname rather than a route ID, you can convert it with [`match`](/docs/kit/$app-paths#match) from `$app/paths`: ```js // @errors: 7031 import { match } from '$app/paths'; import { preloadCode } from '$app/navigation'; const matched = await match('/blog/hello-world'); if (matched) await preloadCode(matched.id); ``` Unlike `preloadData`, this won't call `load` functions. Returns a Promise that resolves when the modules have been imported.
```dts function preloadCode( id: import('$app/types').RouteId ): Promise; ```
## preloadData Programmatically preloads the given page, which means 1. ensuring that the code for the page is loaded, and 2. calling the page's load function with the appropriate options. This is the same behaviour that SvelteKit triggers when the user taps or mouses over an `` element with `data-sveltekit-preload-data`. If the next navigation is to `href`, the values returned from load will be used, making navigation instantaneous. Returns a Promise that resolves with the result of running the new route's `load` functions once the preload is complete.
```dts function preloadData(href: string): Promise< ( | { type: 'loaded'; data: Record; } | { type: 'redirect'; location: string; } | { type: 'error'; error: App.Error; } ) & { status: number; } >; ```
## pushState
Use `goto(url, { state, shallow: true })` instead.
Programmatically create a new history entry with the given `page.state`. Used for [shallow routing](/docs/kit/shallow-routing).
```dts function pushState( url: string | URL, state: App.PageState ): Promise; ```
## refreshAll Causes all currently active remote functions to refresh, and all `load` functions belonging to the currently active page to re-run. Returns a `Promise` that resolves when the page is subsequently updated.
```dts function refreshAll(): Promise; ```
## replaceState
Use `goto(url, { state, shallow: true, replace: true })` instead.
Programmatically replace the current history entry with the given `page.state`. Used for [shallow routing](/docs/kit/shallow-routing).
```dts function replaceState( url: string | URL, state: App.PageState ): Promise; ```
## snapshot A lifecycle function that captures state before navigating and restores it when traversing history. By default, the snapshot `id` is generated from the call site. Pass an explicit `id` to keep snapshots stable across deployments or distinguish multiple uses of a shared helper. The optional `reset` callback runs on navigations where there is no captured value to restore, such as when a new history entry is created. Captured values are serialized with the app's transport hook. `snapshot` must be called during a component initialization. It remains active as long as the component is mounted.
```dts function snapshot(options: { id?: string; capture: () => T; restore: (value: T) => void; reset?: () => void; }): void; ```
## AfterNavigate The argument passed to [`afterNavigate`](/docs/kit/$app-navigation#afterNavigate) callbacks.
```dts type AfterNavigate = (Navigation | NavigationEnter) & { type: Exclude; /** * Since `afterNavigate` callbacks are called after a navigation completes, they will never be called with a navigation that unloads the page. */ willUnload: false; }; ```
## BeforeNavigate The argument passed to [`beforeNavigate`](/docs/kit/$app-navigation#beforeNavigate) callbacks.
```dts type BeforeNavigate = Navigation & { /** * Call this to prevent the navigation from starting. */ cancel: () => void; }; ```
## GotoOptions
```dts interface GotoOptions {/*…*/} ```
```dts replace?: boolean; ```
- default `false`
If `true`, replaces the current history entry rather than creating a new one.
```dts replaceState?: boolean; ```
- deprecated Use `replace` instead.
```dts shallow?: boolean; ```
- default `false`
If `true`, updates the URL and `page.state` without navigating.
```dts reset?: boolean; ```
- default `true, or false when `shallow` is true`
If `true`, resets the scroll position (to the top of the page, or to the element matching the URL's `#hash` if there is one) and resets focus (to the ``, or the `autofocus` element if there is one) once the navigation completes. If `false`, the current scroll position and focused element are left alone.
```dts refreshAll?: boolean; ```
- default `false`
If `true`, reruns all `load` functions and queries of the page.
```dts invalidate?: Array boolean)>; ```
Causes any `load` functions to rerun if they depend on one of the URLs.
```dts invalidateAll?: boolean; ```
- deprecated Use `refreshAll` instead.
```dts state?: App.PageState; ```
An optional object that will be available as `page.state`.
```dts persistState?: boolean; ```
- default `false`
If `true`, `page.state` will be restored after a full page reload.
## Navigation
```dts type Navigation = | NavigationExternal | NavigationFormSubmit | NavigationPopState | NavigationLink; ```
## NavigationBase
```dts interface NavigationBase {/*…*/} ```
```dts type: NavigationType; ```
The type of navigation: - `enter`: The app has hydrated/started - `form`: The user submitted a `
` - `goto`: Navigation was triggered by a `goto(...)` call or a redirect - `leave`: The app is being left either because the tab is being closed or a navigation to a different document is occurring - `link`: Navigation was triggered by a link click - `popstate`: Navigation was triggered by back/forward navigation
```dts shallow: boolean; ```
Whether this is a shallow navigation.
```dts from: NavigationTarget | null; ```
Where navigation was triggered from
```dts to: NavigationTarget | null; ```
Where navigation is going to/has gone to
```dts willUnload: boolean; ```
Whether or not the navigation will result in the page being unloaded (i.e. not a client-side navigation).
```dts complete: Promise; ```
A promise that resolves once the navigation is complete, and rejects if the navigation fails or is aborted. In the case of a `willUnload` navigation, the promise will never resolve
## NavigationEnter The navigation that occurs when the app starts/hydrates
```dts interface NavigationEnter extends NavigationBase {/*…*/} ```
```dts type: 'enter'; ```
```dts delta?: undefined; ```
In case of a history back/forward navigation, the number of steps to go back/forward
```dts event?: undefined; ```
Dispatched `Event` object when navigation occurred by `popstate` or `link`.
## NavigationExternal
```dts type NavigationExternal = NavigationGoto | NavigationLeave; ```
## NavigationFormSubmit A navigation triggered by a ``
```dts interface NavigationFormSubmit extends NavigationBase {/*…*/} ```
```dts type: 'form'; ```
```dts event: SubmitEvent; ```
The `SubmitEvent` that caused the navigation
## NavigationGoto A navigation triggered by a `goto(...)` call or a redirect
```dts interface NavigationGoto extends NavigationBase {/*…*/} ```
```dts type: 'goto'; ```
## NavigationLeave A navigation triggered by the tab being closed, or the user navigating to a different document
```dts interface NavigationLeave extends NavigationBase {/*…*/} ```
```dts type: 'leave'; ```
## NavigationLink A navigation triggered by a link click
```dts interface NavigationLink extends NavigationBase {/*…*/} ```
```dts type: 'link'; ```
```dts event: PointerEvent; ```
The `PointerEvent` that caused the navigation
## NavigationPopState A navigation triggered by back/forward navigation
```dts interface NavigationPopState extends NavigationBase {/*…*/} ```
```dts type: 'popstate'; ```
```dts delta: number; ```
In case of a history back/forward navigation, the number of steps to go back/forward
```dts event: PopStateEvent; ```
The `PopStateEvent` that caused the navigation
## NavigationTarget Information about the target of a specific navigation.
```dts interface NavigationTarget< Params extends AppLayoutParams<'/'> = AppLayoutParams<'/'>, RouteId extends AppRouteId | null = AppRouteId | null > {/*…*/} ```
```dts params: Params | null; ```
Parameters of the target page - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object. Is `null` if the target is not part of the SvelteKit app (could not be resolved to a route).
```dts route: {/*…*/} ```
Info about the target route
```dts id: RouteId | null; ```
The ID of the current route - e.g. for `src/routes/blog/[slug]`, it would be `/blog/[slug]`. It is `null` when no route is matched.
```dts url: URL; ```
The URL that is navigated to
```dts scroll: { x: number; y: number } | null; ```
The scroll position associated with this navigation. For the `from` target, this is the scroll position at the moment of navigation. For the `to` target, this represents the scroll position that will be or was restored: - In `beforeNavigate` and `onNavigate`, this is only available for `popstate` navigations (back/forward button) and will be `null` for other navigation types, since the final scroll position isn't known ahead of time. - In `afterNavigate`, this is always the scroll position that was applied after the navigation completed.
## NavigationType - `enter`: The app has hydrated/started - `form`: The user submitted a `` - `goto`: Navigation was triggered by a `goto(...)` call or a redirect - `leave`: The app is being left either because the tab is being closed or a navigation to a different document is occurring - `link`: Navigation was triggered by a link click - `popstate`: Navigation was triggered by back/forward navigation
```dts type NavigationType = | 'enter' | 'form' | 'leave' | 'link' | 'goto' | 'popstate'; ```
## OnNavigate The argument passed to [`onNavigate`](/docs/kit/$app-navigation#onNavigate) callbacks.
```dts type OnNavigate = Navigation & { type: Exclude; /** * Since `onNavigate` callbacks are called immediately before a client-side navigation, they will never be called with a navigation that unloads the page. */ willUnload: false; }; ```