Changing the URL locale using Next.js router.push is unsuccessful

I am attempting to switch the locale by connecting the onClick event to two separate <div> elements:

import { useRouter } from 'next/router'
// other codes

const router = useRouter()

const changeLocale = (locale) => {
    router.push({
        router: router.pathname,
        query: router.query
    }, router.asPath, { locale })
}

return <div>
    <div onClick={() => changeLocale('en')}>EN</div>
    <div onClick={() => changeLocale('ru')}>RU</div>
</div>

The issue I'm facing is that the URL is not updating. For example, when I am at /en/about and click on the "RU" option, the URL remains as /en/about.

I would like to understand why the router.push function is not behaving as expected in this scenario.

Answer №1

Notice that when using router.push({}), the router property is not accessible!

To manage routing, specify a list of supported locales and the default locale in Next.js for automatic routing handling.

// next.config.js
module.exports = {
  i18n: {
    // List all the locales to be supported in your application
    locales: ['en', 'ru'],
    // Set the default locale to be used when accessing non-locale prefixed paths like `/hello`
    defaultLocale: 'en',
  },
}

If you are using Next.js 12, to add a prefix to the default locale, update the next config as follows:

// next.config.js

module.exports = {
  i18n: {
    locales: ['default', 'en', 'ru'],
    defaultLocale: 'default',
    localeDetection: false,
  },
  trailingSlash: true,
}

Furthermore, to implement custom routing rules, create a new file named middleware.js within your pages directory:

// middleware.js

import { NextRequest, NextResponse } from 'next/server'

const PUBLIC_FILE = /\.(.*)$/

export async function middleware(req: NextRequest) {
  if (
    req.nextUrl.pathname.startsWith('/_next') ||
    req.nextUrl.pathname.includes('/api/') ||
    PUBLIC_FILE.test(req.nextUrl.pathname)
  ) {
    return
  }

  if (req.nextUrl.locale === 'default') {
    return NextResponse.redirect(new URL(`/en${req.nextUrl.pathname}`, req.url))
  }
}

For further information on locale strategies, refer to the Next.js documentation.

Answer №2

The problem I encountered stemmed from having a submenu, which resulted in the router.push with the default locale being triggered again, preventing the route from changing due to no change in locale. One way to address this is by incorporating a validation check in your changeLocale function to determine if a locale has been specified.

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

Selenium Webdriver experiencing issues with running JavaScript code

Looking to extract data from an Aliexpress product page? Take a look at this example. Specifically, I am interested in this section (transaction history). Here is my code snippet: from selenium.webdriver.chrome.options import Options from selenium impor ...

Issue with inline Javascript not functioning correctly when partial is rerendered in Ruby on Rails version 3.1

I am facing an issue in my project where inline JavaScript in a partial, using some instance variables, does not run when the partial is rerendered after a successful ajax call. Could someone please provide guidance on how to solve this problem? For exam ...

Organizing outcomes from a for each function into an array using javascript

I have a form with multiple values of the same name, and I need to arrange this data in an array before sending it via AJAX. However, when I try to do this using the .push function, I encounter an error that says "Uncaught TypeError: dArray.push is not a f ...

Collaboratively utilizing resources among various NPM Workspaces

Currently, I am working on a React project using NPM Workspaces. I have created an 'assets' workspace within this project to store all images and assets that need to be accessed by other workspaces. The directory structure of the project is as fo ...

Rotating the camera around the origin in Three.js

Hey, I'm having some trouble with what I thought would be a simple task. I have a group of objects at the origin, and I'm trying to rotate a camera around them while always facing the origin. According to the documentation, this code should work: ...

What is the rationale behind allowing any type in TypeScript, even though it can make it more challenging to detect errors during compile time?

Why is it that all types are allowed in TypeScript? This can lead to potential bugs at runtime, as the use of type "any" makes it harder to detect errors during compilation. Example: const someValue: string = "Some string"; someValue.toExponentia ...

What is the best way to create a floating navigation bar that appears when I tap on an icon?

As a beginner in the realm of React, I recently explored a tutorial on creating a navigation bar. Following the guidance, I successfully implemented a sidebar-style navbar that appears when the menu icon is clicked for smaller screen sizes. To hide it, I u ...

What is the process of compiling HTML code?

In controller, I bind the same data like $scope.name = "<div>geetha teko</div>", this name will now be bound to the HTML like {{name}}. When I view it in the browser, it prints as "<div>geetha tek0</div>". Is there a way to only di ...

Blend the power of Node's CommonJS with the versatility of Typescript's ES modules

I currently have a Node.js v10 legacy application that was built using CommonJS modules (require). The entire codebase is written in JavaScript. However, I am considering upgrading the app and refactoring a specific part of it to use TypeScript modules ( ...

What is the process of passing a JavaScript variable to PHP with AJAX?

In the given scenario, I have an HTML file that is intended to display the content of a text file at div id="myDiv". The text file content will be read by PHP. However, there seems to be an issue in retrieving the content from the text file. I need assis ...

The error of "No 'Access-Control-Allow-Origin' header is present on the requested resource" persists even after implementing the Access-Control-Allow-Origin header

I'm trying to retrieve JSON data from a Firebase cloud function. The JSON URL works fine on the browser and my Android app, but I encounter issues when trying to fetch it in my JavaScript code. This results in an error message: No 'Access-Cont ...

Open the overflow div within a table data cell

My goal is to create a drag-and-drop schedule tool similar to Fullcalendar. I have decided to use a table layout with a rectangular div inside each TD cell to represent tasks. <table onDragEnd={dragend}> <tr> <th>0</th> ...

Using Javascript to initialize events based on a variable

This particular plugin is structured in the following way: (function($){ var defaults = { param1:null, param2:null }; var methods = { init:function(params) { var ...

Vue data set is displaying as undefined

Having an issue passing the value and index of an object to a vue method. The method successfully displays the value, but the index remains undefined. Looking for guidance on where the mistake might be. JAVASCRIPT: <div class="select is-info"> ...

Ways to include a CSS file path in a link tag from an npm package

I have recently installed a package using npm. npm install lightgallery Now, I am trying to fill the href attribute of a link with the css file directory of this package. Here is what I have so far: <link rel="stylesheet" href="/node_mod ...

Tips for incorporating the .click function with an overlay

Having some trouble using the .click function in conjunction with jQuery Tools overlay. HTML: <p id="click">Click here:</p> <div class="pop"> <div> <p>Insert text here</p> </div> </div> jQuery func ...

Prisma query that selects categories only if they are linked to an item in a table relation

I am managing two tables, one called categories and the other called items. The categories table is structured like this: model publish_categories { c_id Int @id @default(autoincrement()) name String slug String active Int? } In the items ...

How can I link two separate webpages upon submitting a form with a single click?

Here is a snippet of my code: <form action="register.php" method="post"> <input type="text" name="uname"> <input type="submit" > </form> Within the register.php file, there are codes for connecting to a database. I am looking ...

Tips for presenting HTML source code with appropriate tag coloring, style, and indentation similar to that found in editors

I need to display the source code of an HTML file that is rendered in an iframe. The source code should be shown with proper tag colors and indentations similar to editors like Sublime Text. https://i.stack.imgur.com/IbHr0.png I managed to extract the sour ...

Utilizing the nativescript-loading-indicator in a Vue Native application: Step-by-step guide

I am attempting to incorporate the nstudio/nativescript-loading-indicator package into my Vue Native App, but I am experiencing issues with its functionality. import {LoadingIndicator, Mode, OptionsCommon} from '@nstudio/nativescript-loading-indicato ...