T
TanStack15mo ago
extended-yellow

Redirecting in 'beforeLoad' to change one parameter in the URL

I'm trying to ensure that URLs in the address bar are always in the users current language. For context, as an example, lets say I have in my CMS a model for an article and it has a translatable 'slug' parameter and content. What I want to do is if a user lands on /blog/article/hola to redirect to /blog/article/hello when in English. So far I have managed this with the beforeLoad function on the route and throwing redirect() with my new route. As I do not want to be constructing the URLs myself I am making use of the buildLocation function provided to my beforeLoad function for example:
throw redirect({
to: opts.buildLocation({
from: location.pathname,
params: { slug: 'my-new-slug'},
}).href,
});
throw redirect({
to: opts.buildLocation({
from: location.pathname,
params: { slug: 'my-new-slug'},
}).href,
});
This works fine when on an article page already however when accessing the site and clicking a link on say the home page it doesn't work as it does not find a match for the original route. I can see when debugging this is because its only matching the from location based on the routes at the level the page you are currently on (ie. not looking at child routes?). Also when debugging I saw there is a way to pass through _fromLocation and passing the full ParsedLocation of the page we're about to route to works but obviously this seems to be something internal as its not described anywhere and it begins with an underscore. Is there a way to achieve what I want to achieve without seemingly reaching into the internals and doing something I shouldn't be?
1 Reply
ambitious-aqua
ambitious-aqua15mo ago
Can you please provide a minimal complete example by forking one of the examples on stackblitz?

Did you find this page helpful?