Overview
The router provides four functions for programmatic navigation: push(), replace(), pop(), and goBack(). The push() and replace() functions support multiple convenient input formats.
Navigation Functions
push()
Purpose: Navigate to a new page
Behavior: Adds new entry to history stack
User can: Use back button to return
replace()
Purpose: Replace current page
Behavior: Replaces current history entry
User can: NOT use back button to return to replaced page
pop()
Purpose: Go back in history
Behavior: Equivalent to browser back button
User sees: Previous page from history
Link Format Examples
Both push() and replace() support seven flexible input formats.
Here are code examples for each format:
Format 1: Simple String Path
Use a plain string for direct navigation to static routes:
Format 2: Array with Route Name Only
Use an array with just the route name (requires named routes setup):
Format 3: Array with Route Name and Parameters
Use an array with route name and parameters object:
Format 4: Array with Route Name, Parameters, and Query
Use an array with route name, parameters, and query string object:
Format 5: Object with Route Name Only
Use an object with just the route property:
Format 6: Object with Route Name and Parameters
Use an object with route and params properties:
Format 7: Object with All Options
Use an object with route, params, and query properties for complete control:
Format Comparison
Here's the same navigation using all three formats:
Which format should I use?
- String format: Best for simple, static routes
- Array format: Recommended for named routes - concise and readable
- Object format: Best for complex navigation with many parameters, or when you want maximum clarity
Practical Examples
Form Submission
Login Redirect
Pagination
Conditional Navigation
Back Navigation
Common Patterns
Navigation after API call
Navigate with preserved filters
Multi-step wizard
Best Practices
✅ Do
- Use
replace()for login/logout flows to prevent back button issues - Use named routes with
registerRoutes()for maintainability - Use
awaitwith navigation functions to handle completion - Preserve query parameters when navigating between related views
- Use
pop()instead of hardcoding back navigation
⚠️ Don't
- Don't call navigation functions in a tight loop
- Don't forget to handle navigation errors in try/catch
- Don't hardcode URLs - use named routes instead
- Don't use
push()for redirects after form submission - considerreplace()
TypeScript Support
All navigation functions are fully typed with TypeScript:
Try It Live
See programmatic navigation in action in the example application at /links-demo. The demo includes interactive buttons to test all three formats.
Example App: Check out example-history/src/routes/LinksDemo.svelte for a complete working example
with all navigation formats.