Tips for implementing multi-language URL routing in a Node.js application

I am seeking guidance on how to handle routing for multi-language URLs in Node.js,

Currently, I have the following routes set up where each language generates specific routes as shown below. However, with more than 5 languages, efficiency is becoming a concern.

app.js

app.use('/:lang/detail/:service', serviceRouter);
app.use('/:lang/xhixhi/:service', serviceRouter);
app.use('/:lang/servise/:service', serviceRouter);

app.use('/:lang/about', aboutRouter);
app.use('/:lang/guan-yu-wo-men', aboutRouter);
app.use('/:lang/tentang-kami', serviceRouter);

app.use('/:lang/contact', contactRouter);
app.use('/:lang/lian-xi-wo-men', contactRouter);
app.use('/:lang/kontak', contactRouter);

Answer №1

It is advisable to utilize a table-driven approach instead of duplicating code wherever possible.

const routeInfo = [
   {url: "/:lang/{tag}/:service", words: ["detail", "xhixhi", "servise"], router: serviceRouter}, 
   {url: "/:lang/{tag}", words: ["about", "guan-yu-wo-men", "tentang-kami"], router: aboutRouter}, 
   {url: "/:lang/{tag}", words: ["contact", "lian-xi-wo-men", "kontak"], router: contactRouter}, 
];

To create all the routes, iterate through the table:

for (let info of routeInfo) {
    for (let word of info.words) {
       let url = info.url.replace("{tag}", word);
       app.use(url, info.router);
    }
}

If a new language needs to be added, simply append it to each word array.

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

Exploring the latest features of Express.js for efficient app routing: a step-by-step guide

It's possible that the title is a bit ambiguous.. however, in the past, I was able to accomplish the following: /* file 1*/ app = express.createServer(); /* main file*/ server = express.createServer(); // route server.get('/whatever', fun ...

Start the CSS3 animation in reverse right away

I am trying to achieve a "flashing" effect by adding the .shown class to my #overlay, causing the opacity to fade in for 2 seconds and then immediately reverse, fading out for another 2 seconds. After experimenting with removing the class, I found that it ...

The requested URL for /users cannot be found when using the Express Router

I'm using express router but I keep getting an error message saying "Cannot GET /users". This is strange because I'm following a tutorial where the instructor did the exact same thing. The users.js file is located in the router folder. Server.js ...

How to handle JavaScript exceptions when encountering a null JSON value?

I am receiving data in JSON format using AJAX from an action in Struts 2 for my view. The data consists of a set of information. For example: {"home": "1234", "room": null} When I try to read data.home, I successfully get the value 1234. However, when a ...

Issue with AngularJS filter not functioning properly

I have a specific situation where I am using an ng-repeat directive in the following manner: {"ng-repeat" => "city in cities() | filter: search"} In this context, each city object is structured like so: { attributes: {name: 'Boston'} } Furt ...

Why do `setTimeout` calls within JavaScript `for` loops often result in failure?

Can you help me understand a concept? I'm not inquiring about fixing the code below. I already know that using the let keyword or an iffe can capture the value of i. What I need clarification on is how the value of i is accessed in this code snippet. ...

Troubleshooting SocketIO connection problems and optimizing performance through clustering

I am facing an issue with my NodeJS app that I am trying to deploy on Heroku. Here is a snippet from the index.js file: Server (port 3030) const http = require('http'); const os = require('os'); const express = require('express&a ...

How can I convert a string to an integer in Node.js/JavaScript in terms of cardinality?

Imagine a scenario where a user can input any string such as "1st", "2nd", "third", "fourth", "fifth", "9999th", etc. The goal is to assign an integer value to each of these strings: "1st" -> 0 "2nd" -> 1 "third" -> 2 "fourth" -> 3 "fifth" -&g ...

Tips for rearranging objects within a jsPDF document to prevent vertical overlap when a table grows in size

I am new to React and Javascript. I have been struggling to find a solution to my issue while trying to create a .pdf document for a customer invoice using "jsPdf" along with its plugin "jspdf-autoTable". So far, everything is being generated correctly by ...

Sequelize is providing a date that is earlier than the one initially received

Hello everyone, I'm facing an issue with Sequelize where it seems to be returning the date from the backend as the day before the actual date passed. Additionally, it is adding a default time of 23:00:00. To elaborate, when a date is selected in the f ...

Is there a way to access a computed property within methods?

Currently, I am utilizing this particular package to implement infinite scrolling in Vue. In order to continuously add new elements during each scroll, I fetch JSON data from my API server and store it in a data object. Subsequently, I divide the array in ...

What is the best way to create random integers using JavaScript?

Is there a way to create a function called drawSomething(x, y, color, boolean) that will generate random integers for the position of x and y on the canvas, randomly select a color from red, yellow, or blue, and randomly assign true or false to the boole ...

Attempting to display items using the map method, pulling in text from an array

I am working with an array state that tracks the text entered by the user in a text field. My goal is to display this text within a component so users can see what they have previously entered. However, I am facing an issue with my Hashtags component when ...

"Combining Node.js, MongoDB, and Vue.js to create a dynamic dependent select dropdown: a step-by-step

Seeking guidance on setting up a dynamic dependent dropdown list using node js, mongoDB and Vue js. As a newcomer to this concept, I'm unsure where to begin. Here is the scenario I am facing: I need assistance in creating 2 dropdown menus for country ...

Error: The node is unable to parse JSON data through the API

After loading a JSON file as a string, attempting to parse it back to JSON and send it as a response: router.get('/todos', (req,res) =>{ let todos = fs.readFile('todos.json', 'utf8',(err, data) =>{ if (err) ...

Creating a function that assigns an anonymous function which in turn returns another anonymous function

Can you explain the difference in JavaScript between these two code snippets? var reader = new FileReader(); reader.onload = (function (theFile) { return function (e) { loadData(e.target.result); }; })(file); reader.readAsText(file); a ...

The issue arises with loading data from the server due to lack of definition of Mongo

I am experiencing a console bug and need assistance. It seems that there is an issue with loading data from the server as I am getting an error stating "Mongo is not defined." C:\Users\Robert\Desktop\FINISH\node_modules\mongod ...

Issue with Calendar Control not loading in Internet Explorer 9 when using ASP

I have been trying to incorporate a calendar control in my code that selects a date and returns it to a text field. It worked perfectly fine on browsers prior to IE 8, but I'm facing issues with IE 9. Can someone help me troubleshoot this problem and ...

Stopping errors are a common occurrence in synchronous AJAX

I recently encountered an issue with my AJAX request setup. In the success callback function, I called a new function to render Google links and made another AJAX call. To address some performance concerns, I attempted to change these asynchronous calls t ...

Node server quickly sends a response to an asynchronous client request

Apologies for my lack of writing skills when I first wake up, let me make some revisions. I am utilizing expressjs with passportjs (local strategy) to handle my server and connect-busboy for file uploads. I believe passport will not have a role in this pr ...