navigate()
Environment: client.
The navigate('/some/url')
function enables you to programmatically switch pages without requiring the user to click a link.
For example, to redirect the user after a successful form submission:
If you want to redirect the user while rendering a page then use
throw redirect()
instead. For example, when redirecting a non-authenticated user to a login page. See Abort >throw redirect()
VSthrow render()
VSnavigate()
.
If you want to programmatically navigate back then use
window.history.back()
.
Options
navigate('/some-url', { keepScrollPosition: true })
: Don't scroll to the top of the page, preserve the scroll position instead. See also:navigate('/some-url', { overwriteLastHistoryEntry: true })
: Don't create a new entry in the browser's history, instead let the new URL replace the current URL. This effectively removes the current URL from the browser history.navigate('/some-url', { pageContext })
: Pass extrapageContext
values to the next page.
history.pushState()
If you want to change the URL completely independently of Vike then use history.pushState()
instead of navigate()
.
You can then implement your navigation handling by listening to the popstate
event.
⚠️You must handle thepopstate
event, otherwise you'll break the browser's back- and forward history button.
Without vike-{react,vue,solid}
If you don't use a UI framework Vike extension vike-react
/vike-vue
/vike-solid
and if you use Server Routing then use window.location.href = '/some/url'
instead of navigate()
(because navigate()
requires Client Routing).
The UI framework Vike extensions
vike-react
/vike-vue
/vike-solid
use Client Routing.