Is it possible to configure route localization in Next.js and next-i18next to function as an URL alias?

Currently, I am utilizing NextJs version 10.0.5 in conjunction with next-i18next version 8.1.0 to localize my application. With the introduction of subpath routing for internationalized routing in NextJs 10, I encountered a situation where I needed to modify page names based on language preferences. For instance, within the pages folder, there exists a file named contact-us. When switching the language to Turkish, the URL would typically be localhost:3000/tr/contact-us. However, I aimed to access the same contact-us page using the URL localhost:3000/bize-ulasin when the language is set to Turkish.

I managed to achieve this through custom routing in express js implemented in the server.js file. Despite the success of implementing custom routes, I encountered a challenge when attempting to retrieve the "locale" variable within the getStaticProps function located in the contact-us file. It appears that the getStaticProps method returned an undefined value for the "locale" variable specifically when accessing the URL localhost:3000/bize-ulasin.

server.js

const { createServer } = require("http");
const { parse } = require("url");
const next = require("next");
const app = next({ dev: process.env.NODE_ENV !== "production" });
const handle = app.getRequestHandler(app);

app.prepare().then(() => {
  createServer((req, res) => {
    const parsedUrl = parse(req.url, true);
    const { pathname, query } = parsedUrl;

    if (pathname === "/bize-ulasin") {
      app.render(req, res, "/contact-us", query);
    }else{
      handle(req, res, parsedUrl);
    }
  }).listen(3000, (err) => {
    if (err) throw err;
    console.log("> Ready on http://localhost:3000");
  });
});

/pages/contact-us-file

import { Fragment } from "react";
import Head from "next/head";
import { useTranslation } from "next-i18next";
import { serverSideTranslations } from "next-i18next/serverSideTranslations";

const ContactUs = () => {
  const { t } = useTranslation("common");
  return (
    <Fragment>
      <Head>
        <title>Contact-Us</title>
      </Head>
    </Fragment>
  );
};

export const getStaticProps = async ({ locale }) => {
  console.log(locale); // Returns undefined when using the URL localhost:3000/bize-ulasin.
  return {
    props: {
      ...(await serverSideTranslations(locale, ["common"])),
    },
  };
};

export default ContactUs;

My primary concern revolves around accessing the "locale" variable within the getStaticProps function. Moreover, I seek insights into how to leverage the following URLs while utilizing the same page file:

->localhost:3000/contact-us
->localhost:3000/bize-ulasin

Answer №1

Today, I encountered a similar issue and managed to find a solution.

The first step is to remove the server.js file. In Next.JS 10, using server.js can cause conflicts with i18n routes, preventing you from retrieving locale data in getStaticProps.

NextJS offers a convenient feature called rewrites, which we can use instead of the server.js file. For instance, if you have a page named contact-us-file, you can update your next.config.js file as follows:

const { i18n } = require('./next-i18next.config')

module.exports = {
    i18n,
    async rewrites() {
        return [
            {
                source: '/contact-us',
                destination: '/en/contact-us-file',
            },
          {
                source: '/bize-ulasin',
                destination: '/tr/contact-us-file',
            },
        ]
    },
}

If you are already familiar with the file being imported by Next-i18next, the setup should be straightforward.

After making these changes, try accessing localhost:3000/contact-us and localhost:3000/bize-ulasin to view your contact us page.

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

What steps do I need to take to execute a script that utilizes the mootools library within an asp.net environment

I've been working on a website that includes a mail form. I'm using the Mootools 1.4.3 library along with FormCheck 1.6.js. However, when I click the button, nothing happens except for the page refreshing. I really like this form and want to make ...

Dealing with cross-origin AJAX posting in Node.js处理Node.js中的

My app.js contains the following handler for POST requests: app.all('/', function (req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "X-Requested-With"); next(); }); app.opt ...

Tips for activating swf file autoplay on the mobile edition of WordPress

I recently added a swf file to my WordPress page (https://www.pacifictintlv.com/mobile). However, I have noticed that it does not seem to work properly when viewed on mobile devices. Is there a way to redirect users to the Flash download link if they do ...

Firestore is failing to accept incoming data when the setDoc method is employed

I am encountering an issue with my app's connectivity to the Firestore database when attempting to utilize setDoc. The database is successfully operational for next-auth, creating records as intended. However, the problem arises when trying to enable ...

Using Ajax, transmit an array from javascript to a php function

How can I send an array from JavaScript to PHP using AJAX? I'm not sure how to do this, especially when trying to send it to a PHP function like a controller class. Can someone please correct me if I'm wrong? Below is my current JavaScript code f ...

Showing text on an ajax loader

While making an ajax call, I have implemented functions that are called on success. To enhance user experience, I am displaying a spinner during the call and hiding it once completed. My goal is to show a message along with the spinner to indicate which fu ...

The type 'Observable<void | AuthError>' cannot be assigned to 'Observable<Action>'

I am encountering an error that reads: error TS2322: Type 'Observable<void | AuthError>' is not assignable to type 'Observable<Action>'. Type 'void | AuthError' is not assignable to type 'Action'. Type &a ...

How can a "Loading" message be displayed while external JavaScript is loading?

I have mastered the art of using JS or jQuery to showcase a "Loading" message during the loading process. Currently, I am working on a sizeable web application that relies on various JS dependencies, and I am seeking a way to exhibit a "loading" message wh ...

Creating unique ID tags using AngularJS

I am struggling with creating an HTML structure that looks like this: <ul> <li id="r1_1">Root node 1 <ul> <li id="child_node_1">Child node 1</li> <li id="child_node_2">Child node 2</ ...

Reconfigure a portion of a string using Vue's dynamic replacement feature

Currently tackling a problem. In my possession is a string that essentially consists of HTML code: let htmlTitle = "<a href="/news/sky-sport-hd-in-italia-dal-18-novembr">Sky Sport HD in italia dal 18 novembre</a> | <a href="/news/ecco-il-g ...

Error in JavaScript: Uncaught TypeError - Unable to access the "left" property of an undefined object

This error is really frustrating and I've come across several inquiries regarding this console issue. It's not providing enough information in the chrome console for me to effectively troubleshoot. /** * Adjustment of dropdown menu positio ...

Encountered a hiccup when trying to launch a duplicated Node.js project on my

Hello, unfortunately I am encountering yet another issue after cloning a project from GitHub onto my PC. When running the project, an error is displayed. Does anyone have a solution for this problem? The error message reads: "C:\Program Files (x86)&bs ...

Add JSON data to the div element using AJAX in ASP.NET MVC

I am successfully retrieving JSON data through an AJAX call Below is the AJAX call being made <script> $('#display').click(function () { var vacancyId = $("#vacancy").val(); var model = { vacancyId: vacancyId }; $.aja ...

Sending users to a fixed file using express.js

When working with Express in Node.js, I'm interested in examining a request on a specific path (such as /restricted) and if it meets certain criteria, having the request handled by the static provider to manage caching headers, among other things. If ...

PHP and MySQL form is not being updated with new data

In my database, the fields include: id,name,email_id,address,phone_no,username,password,category,date <?php include_once('connect_to_mysql.php'); if(isset($_POST["submit"])){ $a=mysql_real_escape_string($_POST["name"]); ...

Here is a guide on how to specify function selection values for a total order. By default, the selection will have predetermined values, and upon clicking the sum button,

<tr id=""> <th> <select id="selection" onchange="myFunction()"> <option id="0" value="0">None</option> <option id="1" value="4.00">Women Suit</option> <option id="2" value="10.00">Dres ...

The persistent state is not being saved correctly by Redux-Persist and is instead returning the initial

I have included redux-persist in my project, but for some reason it is not persisting the state as expected. Instead, I keep receiving the initial state whenever I reload the page. Below is the snippet of my root-reducer: import { combineReducers } from & ...

Attempting to modify the information within the #content division of a webpage through the activation of a linked image within a jquery slideshow

I'm completely stuck on this one, even though I'm relatively new to jquery. My goal is to design a webpage where there is a slideshow of products at the top, and when a user clicks on one of the products, it should update the main #content div w ...

Step-by-step guide on utilizing dynamic import feature in NextJS for importing an SDK

I've been experimenting with the WebcamSDK, and it's functioning properly in React but encountering issues in NextJS Within the SDK, there are various exports structured like so: //@/component/sdk/WebcamSDK.js export class Webcam {...} export cl ...

What is the best way to show only one div at a time when selecting from navbar buttons?

To only display the appropriate div when clicking a button on the left navbar and hide all others, you can use this code: For example: If "Profile" is clicked in the left navbar, the My Profile Form div will be displayed (and all others will remain hidde ...