Overview
Referrer tracking automatically captures information about the previous route and makes it
available through navigationContext. This provides a safer and more flexible
alternative to history.back().
Configuration
Enable referrer tracking in your main.js or app initialization file:
Tracking Modes
never
Behavior: Referrer tracking disabled
Use case: Default mode, minimal overhead
Performance: No tracking cost
notfound
Behavior: Track only for 404 routes
Use case: "Go Back" on error pages
Performance: Minimal tracking cost
always
Behavior: Track all navigations
Use case: Analytics, breadcrumbs, "Go Back" everywhere
Performance: Small overhead per navigation
Referrer Object Structure
The referrer object contains complete information about the previous route:
| Property | Type | Description |
|---|---|---|
location | string | Previous route path (e.g., '/documents/123') |
querystring | string | Previous query string without the '?' prefix |
params | object | Previous route parameters extracted from the URL pattern |
routeName | string | null | Named route identifier, or URL path as fallback |
scrollX | number | Horizontal scroll position when user left the previous route |
scrollY | number | Vertical scroll position when user left the previous route |
Basic Usage
Access referrer information in any route component through navigationContext():
✨ goBack() Helper
The goBack() helper function automatically handles:
- Building the return URL with query string
- Restoring scroll position to where the user was before
- Fallback to home page if no referrer exists
Manual Pattern (Alternative)
If you need custom logic, you can manually navigate using referrer data:
push() does NOT restore scroll position.
Use the goBack() helper for automatic scroll restoration.Benefits Over history.back()
| Feature | history.back() | Referrer Tracking |
|---|---|---|
| Works with replace() | ❌ Broken | ✅ Works |
| Access to parameters | ❌ No | ✅ Full params object |
| Access to querystring | ❌ No | ✅ Full querystring |
| Route name access | ❌ No | ✅ Named route support |
| Conditional logic | ❌ Blind navigation | ✅ Inspect before navigating |
| Custom fallback | ❌ May leave site | ✅ Custom fallback (e.g., home) |
| Scroll position restoration | ⚠️ Browser controlled | ✅ Automatic via goBack() |
goBack() helper with referrer tracking for
reliable "Go Back" functionality with automatic scroll restoration.Scroll Position Tracking
When referrer tracking is enabled, the router automatically captures scroll positions,
allowing goBack() to restore the exact scroll position from when the user
left the previous page.
How It Works
Automatic Capture
When you navigate away from a route, the router automatically saves:
scrollX- Horizontal scroll positionscrollY- Vertical scroll position
These values are stored in history.state and the referrer object.
Automatic Restoration
The goBack() helper automatically:
- Navigates to the referrer location
- Restores scroll to
(scrollX, scrollY) - Preserves browser history state
Manual push() does NOT restore scroll.
History.state Persistence
Referrer data (including scroll positions) is stored in the browser's history.state:
What this means:
- Survives page refreshes - Referrer persists even if user refreshes the page
- Browser back/forward works - Native browser navigation preserves referrers
- Cleared on hard reload - Pressing Ctrl+Shift+R or typing new URL clears history
- Works across sessions - History state persists as long as the tab stays open
Example
Common Use Cases
404 Pages
Show "Go Back" button that returns to the last valid route:
Analytics
Track user navigation patterns:
Protected Routes
Avoid going back to failed authorization routes:
Return URLs
Return to original page after login/signup:
Implementation Details
Timing Behavior
On the first navigation after referrer is updated, component $effects may run twice:
- First run: Location changes but referrer not yet injected (sees undefined)
- Second run: navigationContext updates with referrer (sees correct value)
This is expected Svelte 5 behavior and doesn't affect functionality - the UI renders correctly on the second run.
Subsequent navigations are smooth with single $effect runs.
Route Name Tracking
The routeName property captures how the route was navigated to:
- Named route navigation:
push('userProfile', {id: 123})→ routeName = "userProfile" - Path navigation:
push('/user/123')→ routeName = "/user/123"
Best Practices
- Use 'notfound' mode for error pages and 'always' for full analytics
- Check
referrer?.locationbefore navigating back - Provide fallback destinations (e.g., home) when referrer is undefined
- Use
$state.snapshot()when console logging referrer to see actual values - Prefer referrer over
history.back()for reliable navigation
- Don't use 'always' mode if you don't need it (slight performance cost)
- Don't assume referrer will always be present (handle undefined cases)
- Don't navigate back to '/' if that's your current location
- Don't mix
history.back()with referrer-based navigation
Related Features
- Programmatic Navigation - Learn about push(), replace(), and pop()
- Named Routes - Use route names instead of paths
- Navigation Guards - Protect routes with authorization checks