In my NextJS app, I have a language selector that’s visible on every page. When I select a new language, I just want to replace the current URL by appending a query param lang=en
to it.
Here’s the function that replaces the URL:
const changeLanguage = (lang: LanguageID) => { replace({ pathname, query: { ...query, lang }, }); };
In this example, replace
, query
and pathname
are coming from the next router.
Now, everything works for static routes, but I’m unable to make it work for dynamic routes. For example, I have the following folder structure:
pages |_customers |__index.tsx |__[customerId].tsx
If I’m on http://localhost/customers
and I change my language to English, the URL changes to http://localhost/customers?lang=en
which is what I want. However, if I’m on http://localhost/customer/1
and I change my language to English, the URL changes to http://localhost/customers/[customerId]?customerId=1&lang=en
, instead of the URL I’m expecting http://localhost/customers/1?lang=en
.
Now, I know that I could use asPath
on the router, and reconstruct the query string object by appending lang
to it, but I feel that it’s something that should be build into Next. Also, I know it could be easily done with vanilla JS, but it’s not the point here.
Am I missing something? Is there an easier way to append query params to a dynamic route without doing a server-side re-rendering?
Thanks
Advertisement
Answer
Just add more param to current router then push itself
const router = useRouter(); router.query.NEWPARAMS = "VALUE" router.push(router)