T
TanStack13mo ago
sensitive-blue

How To Get Previous URL

Is there a way to get the previous URL (the URL of the page that was navigated from) in TanStack Router? I already know how to store values in search params , path params or state params, so please let me know if there are any other way.
1 Reply
rare-sapphire
rare-sapphire13mo ago
When creating the router, you can use the .subscribe method to setup a callback to store the URL in sessionStorage.
const router = createRouter({ ... })

router.subscribe('event_name_here', ({ fromLocation }) => {
window.sessionStorage.setItem('previousUrl', fromLocation.href)
})
const router = createRouter({ ... })

router.subscribe('event_name_here', ({ fromLocation }) => {
window.sessionStorage.setItem('previousUrl', fromLocation.href)
})
You can select the correct event from here: https://tanstack.com/router/latest/docs/framework/react/api/router/RouterEventsType
RouterEvents type | TanStack Router React Docs
The RouterEvents type contains all of the events that the router can emit. Each top-level key of this type, represents the name of an event that the router can emit. The values of the keys are the event payloads. `tsx

Did you find this page helpful?