I am currently working on implementing localization in my project using Next.js. However, I am not satisfied with the default built-in localization method, especially when navigating on dynamic routes. Can anyone on Stackoverflow help me find a solution to this issue?
There is a website called gamerpay.gg which handles localization exactly how I would like it. The localization changes seamlessly without reloading the page, even on dynamic routes. It is known that they also use Next.js for their website.
If you check out Gamerpay.gg, you will notice a localization dropdown in the upper navbar. Give it a try to understand what I mean.
The reloading of the browser window is currently not important for me. What matters most is fixing the dynamic routing with localization.
Let's take a look at some code:
I am utilizing the built-in locale switcher from Next.js with the Link component:
<Link href="" locale="en">
<a className={styles.flag} id="lang_switcher">
<Image src="/flags/en.png" height={20} width={20} layout="fixed" />
</a>
</Link>
When I am on the root path ("/"), the localization works perfectly. However, when moving to a dynamic route, the success fades away.
It is essential to note that the Link component above is present on every page within my footer component.
Now, here lies the issue: http://localhost:3000/p/4829/ If I visit this URL normally, everything functions correctly. But, if I click the language switcher in the footer while on this page, the URL changes to http://localhost:3000/en/p/[post_id]/
Based on the official documentation, there doesn't seem to be an easy fix for this. It might require some workarounds. Hence, I turn to the Stackoverflow community to seek a better approach in order to maintain the URL integrity and avoid any disruptions caused by the localization button.
!Woop Woop!
=== UPDATE ===========================
Alright, so after digging into the Next.js router, I discovered an "asPath" object within it. By incorporating this "router.asPath" into my href, I can ensure the correct page remains displayed during translation. I won't mark this as my definitive answer until I've thoroughly tested it. :D
<Link href={router.asPath} locale="en">
<a className={styles.flag} id="lang_switcher">
<Image src="/flags/en.png" height={20} width={20} layout="fixed" />
</a>
</Link>