Globalized Navigation in Next.js

Is there a way for Nextjs to automatically detect the user's country based on the cookies from Cloudflare and incorporate it into the URL? We want to personalize our site for specific countries without manually listing them all out in different languages. Nextjs docs suggest the following configuration:

i18n: {
    locales: ['en-US', 'fr', 'nl-NL'],
    defaultLocale: 'en-US', 
}

I would prefer not to manually specify all countries in both English and Arabic. Is there a method to dynamically detect the country and adjust the URL accordingly? Or should we only list the countries we are interested in and have a default for the rest of the world? I don't want to create separate common.json files for each country, such as en-US and en-UK. I would like them to be subdirectories in the URL but still read from en/common.json.

Answer №1

If you're looking for a great resource on internationalization, be sure to check out the next-i18next library on GitHub. They provide thorough documentation for common use cases. To address your specific query about setting the locale of the Next.js router in next-i18next, you can achieve this with the following code snippet:

const { i18n } = useTranslation();

// Here are sample locale options, you can retrieve actual values from your Cookie
const localeOptions = [
  { language: 'en', code: 'USA' },
  { language: 'es', code: 'ESP' },
];

const changeLanguage = (language: string) => {
  i18n.changeLanguage(language);
  router.push(`/${language}${router.asPath}`, `/${language}${router.asPath}`, { locale: language });
};
    

If you have any further questions, feel free to reach out!

Answer №2

Next.js allows for automatic browser detection, but this feature can be disabled by including localeDetection: false in your settings.

Click here for more information on automatic locale detection in Next.js

To change the locale, you can modify the _document.jsx file:

class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const initialProps = await Document.getInitialProps(ctx);
    // locale is in ctx.locale

    return { ...initialProps, locale: ctx?.locale || "ar" };
  }

  render = () => (
    <Html
      dir={this.props.locale === "ar" ? "rtl" : "ltr"}
      lang={this.props.locale}
    >
      <Head>
        <link rel="icon" href="" type="image/ico" sizes="16x16"></link>
        <script
          dangerouslySetInnerHTML={{
            __html: `history.scrollRestoration = "manual"`,
          }}
        />
      </Head>
      <body>
        <Main />
        <NextScript />
      </body>
    </Html>
  );
}

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

Submitting a form and obtaining results without relying on jQuery

Finding information on how to accomplish this task without using jQuery has proven to be a challenge. It seems like everyone is pushing for jQuery for even the simplest tasks nowadays. Despite avoiding unnecessary use of jQuery in creating a rich experienc ...

Swapping out image sources using a React Hook that includes an onClick event

Despite my best efforts, I have yet to find a solution to this problem. To keep things brief, I am attempting to implement a dark mode toggle in my React application, but my current method feels like a hack. The main issue I am facing is changing the imag ...

Encountering issue with Konva/Vue-Konva: receiving a TypeError at client.js line 227 stating that Konva.Layer is not a

I am integrating Konva/Vue-Konva into my Nuxtjs project to create a drawing feature where users can freely draw rectangles on the canvas by clicking the Add Node button. However, I encountered an error: client.js:227 TypeError: Konva.Layer is not a constr ...

What is the best method for converting a variable with HTML content into a printable string?

In an attempt to display user-entered data from a text box to an HTML div, there seems to be an issue when the data contains HTML content. Instead of displaying the content as a string, it shows it as HTML elements. For example: let text = "<h1>Worl ...

Transform the text area in preparation for a GET request

Trying to figure out how to pass the text from a textarea into the source attribute of an image tag while retaining all formatting, including line breaks. After some research, it seems that the best way to accomplish this is by base 64 encoding the text a ...

ALSO, various criteria

function findLogicalAND(){ let result; let index; for (index = 0; index < arguments.length; index++){ result = arguments[index] && arguments[index+1]; } return result; } console.log(findLogicalAND(true, true, false, false)); I want to r ...

Using Protractor to extract text from multiple paragraphs

How do I retrieve the values of all paragraphs (p) at once? Below is an example of how my inspect view appears: "Testing sample one." "Testing sample two." And here is a snippet of my code to extract the value of id 'run': browser.findElement ...

Is it possible to set up a server with 'app' as the designated request handler?

When working with NodeJS, server creation can be done simply by using: http.createServer(function(req,res) { /* header etc. */}); However, as I delved into using express, the server was automatically created for me. Moving on to learning about sockets, I ...

Failing to retrieve data from Ajax response

When handling requests in a servlet, the following code snippet processes the request received: Gson gson = new Gson(); JsonObject myObj = new JsonObject(); LoginBean loginInfo = getInfo(userId,userPwd); JsonElement loginObj = gson.toJsonTree(loginInfo) ...

Before the hydration process in Next.js, followed by the hydration in Next.js, and ultimately leading to the First Content

I am curious about the significance of the timing metrics Next.js-before-hydration and Next.js-hydration, and how they connect with FCP. My question pertains to a NextJS application that utilizes server-side rendering and hooks on the client side. In the ...

Optimal technique for adding elements to the DOM using ngFor

My application features a websocket connected to an ngFor loop that populates data from approximately 100 records. Each entry in the list has a button with a click event attached, triggering the creation of a loading spinner via a 'div' element w ...

What is the AngularJS equivalent of prevAll() and nextAll() functions in jQuery?

Currently, I am working on a project that involves AngularJS and I'm having trouble finding an example that fits my needs... With AngularJS, I know how to apply a class when an element is clicked, but how can I add a class to all previous items and r ...

Merge the xAxis functionality with Highcharts

My issue involves a chart generated by highcharts.js. The problem arises with a line chart consisting of 5 values (5 points), each displayed on the xAxis as follows: from value 1 to value 2: 0, 0.25, 0.5, 0.75, 1. I am looking to modify this display and re ...

Struggling to animate the selector of a nested div in Jquery?

Despite trying numerous variations, I am struggling to identify the correct selector of a nested div. The goal is to animate this particular div, but since no animations are taking place, I suspect that I have not selected the right element. Here is the a ...

What is the best way to differentiate between several elements inserted via JavaScript in my HTML code?

I'm attempting to replicate the image below using HTML and JavaScript: https://i.sstatic.net/kvmqk.jpg So far, this is what I have: https://i.sstatic.net/8iHfB.png Here's my JavaScript code: function createLink(text, parentElement) { var ...

Manipulating nested JSON objects with AngularJS by adding and pushing the data

I am looking at a JSON object structured like this : { "Name": "Shivansh", "RollNo": "1", "Stream": "CSE", "OverallScore": "76", "Semester": [ { "SemesterName": "FY-2012 - 1", "TotalScore": "78.00", ...

Various array outcomes are produced by identical JavaScript (SAP UI5) code

Utilizing cachebuster to identify the modified file in the application structure. Javascript code snippet: https://i.sstatic.net/CZGfW.png Ineffective Array result: https://i.sstatic.net/D6MdS.png Effective Array result: https://i.sstatic.net/pQCIh.p ...

Every time I refresh the page, my table is getting filled with blank rows

I created a simple example featuring a form and some PHP/JavaScript code. The JavaScript is used for form validation, while the PHP is utilized to update a MySQL table. function checkForm(){ var x = document.forms['form1']['first'] ...

Executing a function every time a prop is updated within the component

I have a prop named transcript in one of my components. Whenever I speak a voice intent, it gets updated. I want to execute a function every time the transcript changes and pass the transcript as an argument. In this code snippet, I attempted to use an On ...

Unable to utilize query parameters with an ExpressJS API on localhost

Within my index.js file app.use('/api/v1/users', userRouter) In the Router file router.get("/:id", getUserDataById); When using Postman: The GET URL I am using is: http://localhost:3000/api/v1/users?id=120622 The error message is: C ...