React to navigation events with lifecycle hooks that run before, during, and after navigation.
/**
* Register callback to run before navigation
* @param callback - Function that receives navigation details
*/
function beforeNavigate(
callback: (navigation: BeforeNavigate) => void
): void;
interface BeforeNavigate {
from: { route: { id: string | null }; url: URL; params: Record<string, string> } | null;
to: { route: { id: string | null }; url: URL; params: Record<string, string> } | null;
type: 'form' | 'leave' | 'link' | 'goto' | 'popstate';
willUnload: boolean;
delta?: number;
cancel(): void;
}Usage:
import { beforeNavigate } from '$app/navigation';
beforeNavigate(({ from, to, cancel }) => {
if (hasUnsavedChanges) {
if (!confirm('Leave without saving?')) {
cancel();
}
}
});/**
* Register callback to run after navigation completes
* @param callback - Function that receives navigation details
*/
function afterNavigate(
callback: (navigation: AfterNavigate) => void
): void;
interface AfterNavigate {
from: { route: { id: string | null }; url: URL; params: Record<string, string> } | null;
to: { route: { id: string | null }; url: URL; params: Record<string, string> } | null;
type: 'enter' | 'form' | 'link' | 'goto' | 'popstate';
willUnload: boolean;
delta?: number;
}Usage:
import { afterNavigate } from '$app/navigation';
afterNavigate(({ from, to }) => {
// Track page view
analytics.track('pageview', {
from: from?.url.pathname,
to: to?.url.pathname
});
});/**
* Register callback during navigation (for view transitions)
* @param callback - Function that receives navigation details
*/
function onNavigate(
callback: (navigation: OnNavigate) => void
): void;
interface OnNavigate {
from: { route: { id: string | null }; url: URL; params: Record<string, string> } | null;
to: { route: { id: string | null }; url: URL; params: Record<string, string> } | null;
type: 'form' | 'link' | 'goto' | 'popstate';
willUnload: boolean;
delta?: number;
}Usage:
import { onNavigate } from '$app/navigation';
onNavigate(() => {
if (!document.startViewTransition) return;
return new Promise(resolve => {
document.startViewTransition(async () => {
resolve();
await new Promise(r => setTimeout(r, 0));
});
});
});/**
* Disable automatic scroll handling for current navigation
*/
function disableScrollHandling(): void;Usage:
import { disableScrollHandling } from '$app/navigation';
import { onMount } from 'svelte';
onMount(() => {
disableScrollHandling();
// Custom scroll behavior
window.scrollTo(0, savedPosition);
});beforeNavigate can cancel navigation with cancel()afterNavigate runs after new page is renderedonNavigate is for view transitions APIenter: Initial app hydration (AfterNavigate only)leave: Leaving app (BeforeNavigate only)form: Form submission via GETlink: <a> clickgoto: Programmatic navigationpopstate: Back/forward buttonwillUnload: true if leaving the appdelta: History stack change (e.g., -1 for back button)