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

The router provides automatic referrer tracking with configurable modes and complete previous route information including parameters and route names.

Configuration

Enable referrer tracking in your main.js or app initialization file:

Enable referrer tracking
 

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:

Referrer object structure
 
PropertyTypeDescription
locationstringPrevious route path (e.g., '/documents/123')
querystringstringPrevious query string without the '?' prefix
paramsobjectPrevious route parameters extracted from the URL pattern
routeNamestring | nullNamed route identifier, or URL path as fallback
scrollXnumberHorizontal scroll position when user left the previous route
scrollYnumberVertical scroll position when user left the previous route

Basic Usage

Access referrer information in any route component through navigationContext():

Component with referrer-based navigation
 
✨ 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:

Manual navigation (without scroll restoration)
 
⚠️ Note: Manual push() does NOT restore scroll position. Use the goBack() helper for automatic scroll restoration.

Benefits Over history.back()

Featurehistory.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()
Recommended: Use 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 position
  • scrollY - Vertical scroll position

These values are stored in history.state and the referrer object.

Automatic Restoration

The goBack() helper automatically:

  1. Navigates to the referrer location
  2. Restores scroll to (scrollX, scrollY)
  3. 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:

  1. First run: Location changes but referrer not yet injected (sees undefined)
  2. 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.

Note: The double-run only happens during development when console logging. The UI always displays correctly because reactive updates happen before render.

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"
Named route tracking example
 

Best Practices

✅ Do:
  • Use 'notfound' mode for error pages and 'always' for full analytics
  • Check referrer?.location before 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:
  • 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