Implementing Default Language in Next.js 14 for Static Export without URL Prefix: A Step-by-Step Guide

Currently, I am in the process of developing a website using Next.js 14, with the intention of exporting it as a static site for distribution through a CDN (Cloudflare Pages). The website I am working on requires support for internationalization (i18n) to cater to multiple languages. To achieve this, I have organized a folder structure dedicated to language support that follows this format:

- [language]
  -- layout.tsx  // generateStaticParams with potential languages
  -- page.tsx
  -- ...

This setup allows me to access pages with language-specific prefixes in the URL, like /en/example and /de/example.

However, my goal is to introduce a default language (e.g., English) that users can access directly from the root path without any language prefix (/example). It's crucial for me not to redirect users to URLs containing language prefixes for SEO reasons. Additionally, since I am using static export, I cannot employ the rewrite function.

Here are the specific criteria I need to meet:

  1. Directly access default language pages from the root path (e.g., /example for English).
  2. Avoid redirects to URLs with language prefixes (e.g., refrain from redirecting /example to /en/example).
  3. Retain the capability to reach pages in other languages with their respective prefixes intact (e.g., /de/example for German).

I am seeking advice on:

The best approach to implement this behavior with Next.js 14 so that default language pages can be served at the root path devoid of a language prefix. It's essential that this solution remains compatible with Next.js' static export functionality.

If you have any insights, code snippets, or helpful references to documentation related to this issue, they would be greatly appreciated.

Answer №1

If I grasp the essence of your query, Nextjs operates as a file routing system where each page.js/ts or route.js/ts file represents a page within the web application. To align with the structure you outlined in your question, it is essential to organize your folders and files accordingly to prevent duplication in your code.

components
  - HomePage.ts // Common component for languages
  - AboutPage.ts
App
 - layout.tsx
 - page.ts // default language pages
 - about
   -- page.ts
 - contactus
   -- page.ts
 - [language]
   -- layout.tsx
   -- page.ts  // other language pages
   -- about
      --- page.ts
   -- contactus
      --- page.ts

Another approach you could consider is managing language through state management tools like Redux or Zustand, allowing you to translate/fetch data specific to the current language without needing separate about page files.

- layout.tsx
  - page.ts // all language pages
- about
  -- page.ts
- contactus
  -- page.ts

In addition, you can configure your next.config.js as follows:

module.exports = {
  i18n: {
    locales: ['en', 'de'], // Include default and additional languages
    defaultLocale: 'en', // Set default language
  },
};

Answer №2

Within one of my repositories, there is a configuration that displays the default English language on the root page, such as how www.example.com automatically serves the English language without requiring the addition of www.example.com/en for accessing the English language page. However, for other pages, the prefix will dictate the language - for example, www.example.com/de will display the German language page. To accomplish this functionality, I utilized the react-i18n and next-i18n packages.

If you'd like to learn more, feel free to check out this helpful resource: i18n in Next js v14

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

How to Calculate the Time Interval Between Two CORS Requests Using jQuery AJAX

When using jQuery's $.ajax to make a CORS request to a web service, there is typically a pre-flight request followed by the actual POST request. I have observed that when there is a time gap between making two web service calls, both a pre-flight and ...

What is the reason behind the error Generic indexed type in Typescript?

Here is a scenario where I have a specific generic type: type MapToFunctions<T> = { [K in keyof T]?: (x: T[K]) => void; }; It functions correctly in this instance: type T1 = { a: string }; const fnmap1: MapToFunctions<T1> = { a: (x: st ...

Vue does not consistently update HTML when the reference value changes

I am trying to showcase the readyState of a WebSocket connection by utilizing a Ref<number> property within an object and displaying the Ref in a template. The value of the Ref is modified during WebSocket open and close events. However, I am encount ...

Unfortunately, the input type number does not allow for the removal of decimal points

I need assistance with modifying the HTML code below. I want to remove the decimal point from the input field. Could anyone please provide instructions on how to accomplish this? <input type="number" min="0" step="1" ng-pattern="/^(0|[1-9][0-9]*)$/" ...

Removing a comma from a dynamic loop of Material UI Text fields in React can be achieved by accessing

Have a question for you, Currently, I'm utilizing React's material UI Text Field component, When I iterate through the text field from a dynamic array and update the default value sourced from that same array, the default value ends up includin ...

Alter the class of the div element every three seconds

Greetings, I trust everyone is doing well. I am in need of some assistance from your brilliant minds. I have a circular div along with three CSS classes, and my objective is to switch the div's class and update the label text every 3 seconds. Any insi ...

Having trouble deleting the value and deselecting the checkbox item?

Feeling a bit confused about a coding issue I'm facing. The problem lies in the categories listed in my database, which I fetched and used to create a post. Now, I'm attempting to edit that post. The categories are in checkbox format, where check ...

Obtaining a value using the Node.js inquirer package

I'm currently working on a flashcard generator using the node.js inquirer package, but I'm struggling to capture the user's selection. When the user selects an option, I want to be able to log that choice, but right now it's just return ...

How can we integrate fixed-data-table-2 sorting with an existing redux store?

Any help or advice you can offer would be greatly appreciated. I am still fairly new to using react. I recently took on a project for a client that was already in progress, and everything has been going smoothly up until now. I've come across a stumb ...

Whenever I click on the menu icon, the material ui menu component adds an unwanted margin to the right side of my page

This is my customized menu component. <Menu id="My-Custom-Menu" aria-labelledby="My-Custom-Menu" anchorEl={anchorEl} open={open} onClose={handleClose ...

Using nodemailer to send an email with a dynamic variable that holds the HTML content

I am attempting to send a variable containing HTML code from a Vue component using the POST method. My technology stack includes TypeScript, Nuxt.js, Node.js, and Vue.js. const order_list = document.querySelector('table') as HTMLInputElement | n ...

What is the best way to initialize a value asynchronously for React context API in the latest version of NextJS, version

Currently, I'm working on implementing the React context API in my NextJS e-commerce application to manage a user's shopping cart. The challenge I'm facing is how to retrieve the cart contents from MongoDB to initiate the cart context. This ...

Retrieving over 300,000 rows from elasticsearch and saving them as a .csv document

Hi there, I am currently working on a website in nodejs that utilizes an Elasticsearch database. One of my indexes, 'bigData*', contains 366,844 rows with each row consisting of 25 items, each being a different string of varying sizes (with a max ...

The Observable pipeline is typically void until it undergoes a series of refreshing actions

The issue with the observable$ | async; else loading; let x condition usually leads to staying in the loading state, and it requires multiple refreshes in the browser for the data to become visible. Below is the code snippet that I utilized: // TypeScript ...

Issue with integrating Google Spreadsheet as the data source for a Next.JS website: updates are not reflecting on the website pages

The website for this restaurant was created by me, using Google Spreadsheet to populate the menu pages. I chose this method for its simplicity and familiarity to the client. I'm utilizing the google-spreadsheet package to extract necessary informatio ...

Experiencing SyntaxError when utilizing rewire and mocha for Node.js testing. Unexpected token encountered

Trying to test a function exported from a nodejs file, I am utilizing q to manage promises. The function returns a promise that is either resolved or rejected internally through a callback. Within this callback, another function from a different location i ...

Obtain information from express middleware

I am currently working on a project using node.js. As part of my application, I have developed a middleware function that is triggered whenever a GET request is made. This occurs when someone visits the home page, profile page, or any other page within my ...

Create a Referral Program page within a swapping interface similar to the functionalities found in platforms like PancakeSwap, PantherSwap, and

Currently, my goal is to create a referral program page similar to the one found at . I have explored the source code on GitHub for the PantherSwap interface, but unfortunately, I did not come across any references to that specific section. Would you be ...

Having issues displaying the & symbol in HTML from backend data

I recently worked on a project using express handlebars, where I was fetching data from the YouTube API. However, the titles of the data contained special characters such as '# (the ' symbol) and & (the & symbol). When attempting to render the ...

Ways to adjust the font weight within material UI

I've been having some trouble trying to change the font weight of buttons in a navbar. No matter what method I try, it seems to go wrong every time. At first, I created a separate CSS file and set the font weight to bold, but it didn't work. Then ...