Managing locale changes centrally can be tricky. When a user selects a new locale from a list, I use useRouter
to redirect them to the current page in the selected locale like this:
var router = useRouter();
const changeLocale = (selectedLocale) => {
router.push({
pathname: router.pathname,
query: router.query
}, { locale });
}
<div onClick={() => changeLocale('fr')}>Fr</div>
This method works smoothly for URLs without parameters. However, when dealing with URLs containing parameters, things get a bit more complicated. For instance, when a user clicks on a conference that leads to a specific conference page using a Link
:
<Link
href={{
pathname: '/conference/[id]',
query: { id: conf.id }
}}
For example, clicking on a conference may lead the user to example.com/conference/5
. But changing the locale on that page results in a duplicated URL like example.com/conference/5?id=5
. This duplication of parameters can cause issues. Omitting the query
parameter in router.push
triggers an error message:
Error: The provided
href
(/conference/[id]) value is missing query values (id) to be interpolated properly. Read more: https://nextjs.org/docs/messages/href-interpolation-failed
Is there a more effective way to handle rerouting while preserving the URL structure and parameters?