T
TanStack2y ago
deep-jade

navigation middleware

Is there any way to hook in middlewares between navigation attempts being done via Link and useNavigate to perform arbitrary logic and/or short circuit the navigation. I’ve looked into useBlocker and it’s not what I’m looking for (i dont want to impact navigations happening outside tanstack router, ie regular browser/history navigations). The reason I'd like to be able to do this is that I'm using tanstack router in a micro frontend scenario. Some of the routes need to be visited via a full page reload, while other routes are purely client side and work fine as-is. My plan is to annotate the micro frontend routes with a flag using router context, and then with this middleware I'll short circuit the navigation when a navigation is attempted to be made to those type of routes and I'll manually trigger a full page reload. If such a middleware functionality existed, that is. My current approach is to customize the Link and createRouter primitives, essentially monkeypatching this behavior in. I'm wondering if there's a cleaner way to achieve this.
2 Replies
deep-jade
deep-jadeOP2y ago
I think i can use the router subscribe function and use the beforeLoad event
robust-apricot
robust-apricot2y ago
I haven't used subscribe before, but the beforeLoad function of a route should be capable what you are trying to do. You have access to the route's context there and could possibly do something like window.location.reload() there.
export const Route = createFileRoute('/')({
beforeLoad: ({ context }) => {
if (context.fullReload) {
window.location.reload()
}
},
loader: ...,
component: ...,
})
export const Route = createFileRoute('/')({
beforeLoad: ({ context }) => {
if (context.fullReload) {
window.location.reload()
}
},
loader: ...,
component: ...,
})

Did you find this page helpful?