Skip to main content

$app/navigation

import {
	function afterNavigate(callback: (navigation: AfterNavigate) => void): void

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.

afterNavigate
,
function beforeNavigate(callback: (navigation: BeforeNavigate) => void): void

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 === nullnavigation.willUnload is true.

beforeNavigate must be called during a component initialization. It remains active as long as the component is mounted.

beforeNavigate
,
function disableScrollHandling(): void

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.

disableScrollHandling
,
function goto(url: string | URL, opts?: GotoOptions): Promise<void>

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).

@param
url Where to navigate to. Note that if you've set config.paths.base and the URL is root-relative, you need to prepend the base path if you want to navigate within the app.
@param
opts Options related to the navigation
goto
,
function invalidate(resource: string | URL | ((url: URL) => boolean), keepState?: boolean): Promise<void>

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.

// Example: Match '/path' regardless of the query parameters
import { function invalidate(resource: string | URL | ((url: URL) => boolean), keepState?: boolean): Promise<void>

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.

// Example: Match '/path' regardless of the query parameters
import { invalidate } from '$app/navigation';

invalidate((url) => url.pathname === '/path');
@param
resource The invalidated URL
@param
keepState If true, the current page.state will be preserved. Otherwise, it will be reset to an empty object. false by default.
invalidate
} from '$app/navigation';
function invalidate(resource: string | URL | ((url: URL) => boolean), keepState?: boolean): Promise<void>

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.

// Example: Match '/path' regardless of the query parameters
import { invalidate } from '$app/navigation';

invalidate((url) => url.pathname === '/path');
@param
resource The invalidated URL
@param
keepState If true, the current page.state will be preserved. Otherwise, it will be reset to an empty object. false by default.
invalidate
((url: URLurl) => url: URLurl.URL.pathname: string

The pathname property of the URL interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a / character.

MDN Reference

pathname
=== '/path');
@param
resource The invalidated URL
@param
keepState If true, the current page.state will be preserved. Otherwise, it will be reset to an empty object. false by default.
invalidate
,
function invalidateAll(): Promise<void>

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), use refreshAll instead.

@deprecated
Use refreshAll instead. Unlike invalidateAll, refreshAll does not reset page.state.
invalidateAll
,
function onNavigate(callback: (navigation: OnNavigate) => MaybePromise<void | (() => void)>): void

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.

onNavigate
,
function preloadCode(id: import("$app/types").RouteId): Promise<void>

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. If you have a pathname rather than a route ID, you can convert it with match from $app/paths:

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.

preloadCode
,
function preloadData(href: string): Promise<({
    type: "loaded";
    data: Record<string, any>;
} | {
    type: "redirect";
    location: string;
} | {
    type: "error";
    error: App.Error;
}) & {
    status: number;
}>

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 <a> 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.

@param
href Page to preload
preloadData
,
function pushState(url: string | URL, state: App.PageState): Promise<void>

Programmatically create a new history entry with the given page.state. Used for shallow routing.

@deprecated
Use goto(url, { state, shallow: true }) instead.
pushState
,
function refreshAll(): Promise<void>

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.

refreshAll
,
function replaceState(url: string | URL, state: App.PageState): Promise<void>

Programmatically replace the current history entry with the given page.state. Used for shallow routing.

@deprecated
Use goto(url, { state, shallow: true, replace: true }) instead.
replaceState
,
function snapshot<T>(options: {
    id?: string;
    capture: () => T;
    restore: (value: T) => void;
    reset?: () => void;
}): void

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.

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.

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 === nullnavigation.willUnload is true.

beforeNavigate must be called during a component initialization. It remains active as long as the component is mounted.

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.

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).

function goto(
	url: string | URL,
	opts?: GotoOptions
): Promise<void>;

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.

// Example: Match '/path' regardless of the query parameters
import { function invalidate(resource: string | URL | ((url: URL) => boolean), keepState?: boolean): Promise<void>

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.

// Example: Match '/path' regardless of the query parameters
import { invalidate } from '$app/navigation';

invalidate((url) => url.pathname === '/path');
@param
resource The invalidated URL
@param
keepState If true, the current page.state will be preserved. Otherwise, it will be reset to an empty object. false by default.
invalidate
} from '$app/navigation';
function invalidate(resource: string | URL | ((url: URL) => boolean), keepState?: boolean): Promise<void>

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.

// Example: Match '/path' regardless of the query parameters
import { invalidate } from '$app/navigation';

invalidate((url) => url.pathname === '/path');
@param
resource The invalidated URL
@param
keepState If true, the current page.state will be preserved. Otherwise, it will be reset to an empty object. false by default.
invalidate
((url: URLurl) => url: URLurl.URL.pathname: string

The pathname property of the URL interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a / character.

MDN Reference

pathname
=== '/path');
function invalidate(
	resource: string | URL | ((url: URL) => boolean),
	keepState?: boolean
): Promise<void>;

invalidateAll

Use 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), use refreshAll instead.

function invalidateAll(): Promise<void>;

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.

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. If you have a pathname rather than a route ID, you can convert it with match from $app/paths:

import { 
function match(url: URL | string): Promise<{ [K in RouteId]: {
    id: K;
    params: RouteParams<K>;
}; }[RouteId] | null>

Match a path or URL to a route ID and extracts any parameters.

@example
import { match } from '$app/paths';

const route = await match('blog/hello-world');

if (route?.id === '/blog/[slug]') {
	const slug = route.params.slug;
	const response = await fetch(`/api/posts/${slug}`);
	const post = await response.json();
}
@since
2.52.0
match
} from '$app/paths';
import { function preloadCode(id: import("$app/types").RouteId): Promise<void>

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. If you have a pathname rather than a route ID, you can convert it with match from $app/paths:

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.

preloadCode
} from '$app/navigation';
const
const matched: {
    id: string;
    params: Record<string, string>;
} | null
matched
= await
function match(url: URL | string): Promise<{ [K in RouteId]: {
    id: K;
    params: RouteParams<K>;
}; }[RouteId] | null>

Match a path or URL to a route ID and extracts any parameters.

@example
import { match } from '$app/paths';

const route = await match('blog/hello-world');

if (route?.id === '/blog/[slug]') {
	const slug = route.params.slug;
	const response = await fetch(`/api/posts/${slug}`);
	const post = await response.json();
}
@since
2.52.0
match
('/blog/hello-world');
if (
const matched: {
    id: string;
    params: Record<string, string>;
} | null
matched
) await function preloadCode(id: import("$app/types").RouteId): Promise<void>

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. If you have a pathname rather than a route ID, you can convert it with match from $app/paths:

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.

preloadCode
(
const matched: {
    id: string;
    params: Record<string, string>;
}
matched
.id: stringid);

Unlike preloadData, this won't call load functions. Returns a Promise that resolves when the modules have been imported.

function preloadCode(
	id: import('$app/types').RouteId
): Promise<void>;

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 <a> 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.

function preloadData(href: string): Promise<
	(
		| {
				type: 'loaded';
				data: Record<string, any>;
		  }
		| {
				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.

function pushState(
	url: string | URL,
	state: App.PageState
): Promise<void>;

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.

function refreshAll(): Promise<void>;

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.

function replaceState(
	url: string | URL,
	state: App.PageState
): Promise<void>;

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.

function snapshot<T>(options: {
	id?: string;
	capture: () => T;
	restore: (value: T) => void;
	reset?: () => void;
}): void;

AfterNavigate

The argument passed to afterNavigate callbacks.

type AfterNavigate = (Navigation | NavigationEnter) & {
	type: Exclude<NavigationType, 'leave'>;
	/**
	 * 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 callbacks.

type BeforeNavigate = Navigation & {
	/**
	 * Call this to prevent the navigation from starting.
	 */
	cancel: () => void;
};

GotoOptions

interface GotoOptions {}
replace?: boolean;
  • default false

If true, replaces the current history entry rather than creating a new one.

replaceState?: boolean;
  • deprecated Use replace instead.
shallow?: boolean;
  • default false

If true, updates the URL and page.state without navigating.

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 <body>, or the autofocus element if there is one) once the navigation completes.

If false, the current scroll position and focused element are left alone.

refreshAll?: boolean;
  • default false

If true, reruns all load functions and queries of the page.

invalidate?: Array<string | URL | ((url: URL) => boolean)>;

Causes any load functions to rerun if they depend on one of the URLs.

invalidateAll?: boolean;
  • deprecated Use refreshAll instead.
state?: App.PageState;

An optional object that will be available as page.state.

persistState?: boolean;
  • default false

If true, page.state will be restored after a full page reload.

type Navigation =
	| NavigationExternal
	| NavigationFormSubmit
	| NavigationPopState
	| NavigationLink;
interface NavigationBase {}
type: NavigationType;

The type of navigation:

  • enter: The app has hydrated/started
  • form: The user submitted a <form method="GET">
  • 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
shallow: boolean;

Whether this is a shallow navigation.

from: NavigationTarget | null;

Where navigation was triggered from

to: NavigationTarget | null;

Where navigation is going to/has gone to

willUnload: boolean;

Whether or not the navigation will result in the page being unloaded (i.e. not a client-side navigation).

complete: Promise<void>;

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

The navigation that occurs when the app starts/hydrates

interface NavigationEnter extends NavigationBase {}
type: 'enter';
delta?: undefined;

In case of a history back/forward navigation, the number of steps to go back/forward

event?: undefined;

Dispatched Event object when navigation occurred by popstate or link.

type NavigationExternal = NavigationGoto | NavigationLeave;

A navigation triggered by a <form method="GET">

interface NavigationFormSubmit extends NavigationBase {}
type: 'form';
event: SubmitEvent;

The SubmitEvent that caused the navigation

A navigation triggered by a goto(...) call or a redirect

interface NavigationGoto extends NavigationBase {}
type: 'goto';

A navigation triggered by the tab being closed, or the user navigating to a different document

interface NavigationLeave extends NavigationBase {}
type: 'leave';

A navigation triggered by a link click

interface NavigationLink extends NavigationBase {}
type: 'link';
event: PointerEvent;

The PointerEvent that caused the navigation

A navigation triggered by back/forward navigation

interface NavigationPopState extends NavigationBase {}
type: 'popstate';
delta: number;

In case of a history back/forward navigation, the number of steps to go back/forward

event: PopStateEvent;

The PopStateEvent that caused the navigation

Information about the target of a specific navigation.

interface NavigationTarget<
	Params extends AppLayoutParams<'/'> =
		AppLayoutParams<'/'>,
	RouteId extends AppRouteId | null = AppRouteId | null
> {}
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).

route: {}

Info about the target route

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.

url: URL;

The URL that is navigated to

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.
  • enter: The app has hydrated/started
  • form: The user submitted a <form method="GET">
  • 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
type NavigationType =
	| 'enter'
	| 'form'
	| 'leave'
	| 'link'
	| 'goto'
	| 'popstate';

OnNavigate

The argument passed to onNavigate callbacks.

type OnNavigate = Navigation & {
	type: Exclude<NavigationType, 'enter' | 'leave'>;
	/**
	 * 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;
};

Edit this page on GitHub llms.txt