What is the best way to eliminate the [lang tag] from a URL in Next.js?

I am looking to eliminate either the /en or the /it from the URL without explicitly adding it. i18next seems to be doing it automatically, and I am unsure how to disable this behavior. I simply want it to happen in the background.

https://i.stack.imgur.com/9Z79L.png

Is there an option I can add to prevent this, or is there nothing that can be done?

Here is my current code:

import i18n from 'i18next'
import Backend from 'i18next-http-backend'
import LanguageDetector from 'i18next-browser-languagedetector'
import { initReactI18next } from 'react-i18next'

i18n
  .use(Backend)
  .use(LanguageDetector)
  .use(initReactI18next)
  .init({
    fallbackLng: 'en',
    debug: true,

    interpolation: {
      escapeValue: false,
    },
    react: {
      useSuspense: false,
    },
  })

export default i18n

I include this on the page where I want to enable translation

import { useTranslation } from 'react-i18next';

function MyComponent: ReactElement {
    const [isEnglish, setIsEnglish] = useState(true);
    const { t, i18n } = useTranslation();
    const handleClick = () => {
        setIsEnglish(!isEnglish);
        i18n.changeLanguage(!isEnglish ? 'en' : 'it');
    }
    return <>My stuff</>
}

As mentioned, it appends the route with /[language code]. Is there a way to remove it and handle it in the "background" instead?

Thank you for your help!

Answer №1

Inside your next.config.js.

i18n: {
  automaticLocaleDetection: false,
}

This has successfully resolved an issue for me.

Answer №2

If you're facing a similar issue, this solution may work for you too.

  • To access the current active language in Next.js, you can use the useRouter hook:
import { useRouter } from "next/router";
const router = useRouter();
const active_language = router.locale;

  • You can retrieve the full URL of your application using the window object:
const window_url = window.location.href;

Note: Code execution in Next.js occurs first server-side, then client-side (which includes the window object). You might encounter "Window is not defined" error, in that case, refer to this article.

  • Determine the API URL based on the active language set,

Assuming the default language is set to "en":

let api_url = "";
if(active_language === "en") {
    api_url = `${window_url.substr(0, window_url.lastIndexOf("/"))}/`;
    console.log(window_url) // http://localhost:3000/shop
    console.log(api_url) // http://localhost:3000/
};

And for the secondary language "ar":

if(active_language === "ar") {
    api_url = window_url.substr(0, window_url.lastIndexOf("/") - 2);
    console.log(window_url) // http://localhost:3000/ar/shop
    console.log(api_url) // http://localhost:3000/
};
  • Your API URL will remain consistent even when switching between locales:
fetch(`${api_url}/api/hello`);

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

NUXT: Module node:fs not found

Encountering an error when running yarn generate in a Kubernetes container during production. The same command works fine locally and was also functioning properly in production up until last week. Error: Cannot find module 'node:fs' Require stac ...

Children components in Vue.js are receiving an undefined props object

Within my application, I am working with a parent and child component. The parent component directly includes the child component, which needs to access data from the parent. This data is fetched from a REST API within the parent component. However, when t ...

Tips for deploying your next.js application on AWS and determining the entry file for the server

I am currently working on a project using Next.js. The image below showcases my folder structure. On my local machine, I can successfully run npm build and npm start commands. The build process completes without any issues and the pages display correctly. ...

Execute React program within VM Azure

After setting up my React application on Azure's virtual machine, I encountered an issue. When trying to access the public URL (DNS) of the VM, I received a "site can't be reached" message. This is the process I followed to launch my project on ...

Is there a way to access comprehensive data pertaining to an ID through Ajax?

I need help with an Ajax call. Below is the code I currently have: $.ajax({ async: true, url: 'test/', type: 'POST', datatype: 'text json', data: { id: id, }, success: function(data) { // Retrieve the da ...

Utilizing any folder as a static directory in Reactjs: A Step-by-Step Guide

My website is built on React and runs smoothly. However, I also maintain a blog using Wordpress. Whenever I try to integrate the blog content into my website by placing it in the blog directory, I encounter a 404 error because React manages everything ex ...

Sequelize - utilizing the where clause with counting

I have three models that extend Sequelize.Model and I have generated migrations for them. The associations are set up as follows: Cat Cat.belongsToMany(Treat, { as: 'treats', through: 'CatTreat', foreignKey: 'cat_id', } ...

Is there a method in TypeScript to make an enum more dynamic by parameterizing it?

I've defined this enum in our codebase. enum EventDesc { EVENT1 = 'event 1', EVENT2 = 'event 2', EVENT3 = 'event 3' } The backend has EVENT1, EVENT2, EVENT3 as event types. On the UI, we display event 1, event 2, a ...

The React app was successfully deployed to localhost:3000, but when attempting to access it, the message "This site can't be reached" is displayed. Strangely, the terminal confirms that the app is indeed

I've checked my code thoroughly, but when I deploy it to localhost, something seems off. Even after disabling all the components and running npm install, the issue persists. https://i.stack.imgur.com/i04eY.png Oddly enough, everything seems fine in ...

What is the best way to evenly distribute 5 items in a row using material-ui's grid system?

I am trying to evenly put 5 items in a row using a grid system with 12 columns. The value of 2.4 doesn't seem to work for me. Any suggestions on how I can achieve this? Thanks in advance :) Here is the code I have so far: <Grid container spac ...

Issue with next-intl plugin when choosing enum-based values is not functioning correctly

For my next.js project (version 13.4), I was in need of next-intl translation support. I followed the official example provided at The example mentioned to define the following code in the 'en.json' file: "message": "{gender, sele ...

Encountering an issue when retrieving data from Firebase Firestore in NEXT.JS with Firebase SDK Firebase v9 results in an error message

Greetings! I am currently trying to retrieve data from Firebase Firestore by following a tutorial on Firebase v9. However, I encountered an error message that says "FIRESTORE (9.8.4) INTERNAL ASSERTION FAILED: Unexpected state". Below is the code snippet: ...

Find the JavaScript code that selects the previous value chosen

When working with a select in React, I am facing an issue where the console.log is returning the last value selected instead of the current one. For instance, if I select 4 followed by 3 and then 5, the code will display 1 (default value), then 4, and fin ...

Is it possible to refactor this forwardRef so that it can be easily reused in a function?

Currently, I am in the process of transitioning my application to Material UI V4 and facing challenges with moving my react router Link components into forwardRef wrapped components when setting the 'to' prop programmatically. The code below doe ...

A simple program capable of holding two variables

To create a calculator, I want to implement a process where the user clicks buttons to input numbers into a display box. For instance, clicking 3 and then 2 should display as 32 in the input box. After that, if I click on the "+" button, it should remove t ...

Tips for validating a text field in React Material UI depending on the input from another text field

Currently, I am working with Material UI TextField and encountered an issue where I need to create a code that establishes a dependency between two textfields. For example, if I enter the number 4 in textfield one, then the number in textfield two should ...

What steps should be followed for the initial deployment of a Next.js app and how should re-deployments be handled thereafter?

I recently completed a sample application in Next.js and successfully deployed it with the npm run build command. To ensure a custom server deployment, I've been referring to this informative article from Next.js documentation: Custom Server Article. ...

What is the best way to retrieve the root binding node from a viewmodel in order to apply jQuery.blockUI when performing an AJAX post request?

Within my code, I have a designated DIV element that serves as the root node for applying knockout bindings like so: ko.applyBindings(viewModel, document.getElementById('myContainerDiv')); In all of my viewmodel types, there is a generic post m ...

Ways to insert text into an SVG file

I am currently using vue-svg-map with a USA map. I am trying to display the state code (path.id) on my svg map. Can anyone provide guidance on how to achieve this? <radio-svg-map v-model="selectedLocation" :map="usa" :location-class="getLocation ...

Having trouble getting Laravel Full Calendar to function properly with a JQuery and Bootstrap theme

Using the Laravel full calendar package maddhatter/laravel-fullcalendar, I am facing an issue where the package is not recognizing my theme's jQuery, Bootstrap, and Moment. I have included all these in the master blade and extended it in this blade. ...