Updating the language setting in NextJS without needing to refresh the page

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>

Answer №1

I recently conducted some tests and, as suggested by one of you, I will now share the solution (I completely forgot, oops).

The answer turned out to be using asPath, which worked perfectly.

<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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Icons on Speed-Dial are not aligning to the center

I've been working on creating a Speed Dial feature for a web application, but I can't seem to get the icons to align properly in the Speed Dial menu. Despite following the instructions provided in https://vuetifyjs.com/en/components/floating-act ...

What could be the reason for the cardDetails component, which is supposed to display information received via a Vuex action, not appearing

Recently, I've been diving into Vue and Vuex while working on a small app that showcases events. Users can click on event cards to view more details using the card's ID. I've moved all the code to the Vuex Store, but I'm encountering is ...

Angular 7: Finding the variance between array elements

How can I subtract the values from the first 3 rows of the table? The formula is TVA Collectée - TVA Déductible - TVA Déductible/immo If the result is positive, it should be displayed in the box labeled TVA à Payer. If it's negative, it should g ...

Having trouble getting AngularJS ngCloak to function properly?

My post category page is supposed to display a message if there are no posts. However, the HTML appears briefly when the page loads and then hides. I thought using ngCloak would solve this issue, but it doesn't seem to be working for me. Here's t ...

Sophisticated web applications with Ajax functionalities and intricate layouts powered by MVC frameworks

I am looking to integrate an ajax-driven RIA frontend, utilizing JQuery layout plugin (http://layout.jquery-dev.net/demos/complex.html) or ExtJs (http://www.extjs.com/deploy/dev/examples/layout/complex.html), with... a PHP MVC backend, potentially using ...

How come my post isn't being saved to the page after I refresh it?

Utilizing Javascript, NodeJS, MongoDB, Express Within my application, a user is expected to enter text in an input field and upon clicking the submit button, the text should appear on the page. I have succeeded in posting text to the page; however, after ...

Using an HTML file as the source for an image in the <img src=""> tag is a simple process that can greatly enhance the visual appeal of your webpage

My goal is to utilize an html file as the source for an image file within the <img src=""> tag in order to prevent mixed-content warnings when using an http image over https. For instance: index.html: <img src="./image.html" > image.htm ...

Passing data received from a node.js request (using https.get) to a separate JavaScript file

I'm new to posting here, so my explanation might not be very clear. I am working on a project using node.js to fetch data and pass it to another js file for use in an html file. The structure of my app folder is as follows: -App -node_modules -publi ...

What is the reason behind PHP's json_encode disregarding empty arrays?

Here is my JavaScript code that sends data to a PHP function: <script> var mydata = { id:123, name: 'mike', orders: [] }; $.ajax({ type: 'POST', ...

Tips for handling tasks with javascript in mongodb

The Mongo database is set up with a sharding structure of 3 Shards named TestSharding. Additionally, the script for this configuration can be written in JavaScript. I am tasked with developing a program that identifies whether a file is in .json or .csv f ...

Transferring JSON data from JavaScript to ASP.NET

In my web app, the backend is built in ASP.net. The ajax call I'm using is a standard get request. $.ajax({ url: 'myurl/updatejson', contentType: "application/json; charset=utf-8", data: data, success: function (data) { ...

Error encountered while parsing a file: JSON parsing failed due to an unexpected token 'g' at position

https.get('example.com/phpfilethatechoesandimtryingtograbtheecho.php', (res) => { console.log('statusCode:', res.statusCode); onsole.log('headers:', res.headers); res.on('data', (d) => { return ...

Using a Do/While loop in combination with the setTimeout function to create an infinite loop

Having trouble with this script. The opacity transition works fine, but there seems to be an issue with the loop causing it to run indefinitely. My goal is to change the z-index once the opacity reaches 0. HTML <div class="ribbon_services_body" id="ri ...

What is the syntax for populating an attribute on the same line as v-for in Vue.js?

I am currently working on a simple loop utilizing Vue to iterate over an array of objects and populate table rows. <tr v-for="user in users"> <td>{user.name}</td> <td>{user.id}</td> </tr> However, I also need to as ...

Trying to call an applet method using JavaScript will not be successful

When trying to invoke methods of a Java applet using JavaScript, I encounter an issue that requires the site to be added to trusted sites and security set to low in order for it to work properly. Otherwise, an error is thrown: Microsoft JScript runtime ...

Displaying pictures under specific conditions

I've recently completed the coding and CSS for my website after working on it for quite some time. Now, I want to enhance it by incorporating new features. The website is fully operational and generates revenue primarily through Google AdSense. I am i ...

Issue with jQuery: submit() function not behaving as expected when navigating back in history

Incorporating jQuery's submit() method in order to perform basic form verification prior to redirecting the user to the subsequent page. $(document).ready(function(){ $("form").submit(function() { // carry out form validation and set erro ...

Locate the user, repository, and file path within a GitHub URL

How can I extract the user, repo, and path from a Github URL pasted into a form in order to make API requests? For example, https://github.com/HubSpot/BuckyClient/blob/master/README.md I have started working on a regex solution to locate the different par ...

How do you typically approach testing Cloud Code on Parse?

While working on developing a substantial amount of business logic in webhooks like beforeSave/afterSave/etc. using Parse.com, I have encountered some challenges as a JavaScript/Parse beginner. The process seems somewhat tedious and I'm questioning if ...

Troubleshooting issue with jQuery animate not correctly scrolling

I am experiencing an issue with my jQuery code that is supposed to scroll a smaller container element within a larger container element when a button is clicked. Despite testing with an alert and verifying that the code is working, the scrolling functional ...