Logo

dev-resources.site

for different kinds of informations.

A Simple Way to Handle Locale-Specific URLs in Express

Published at
8/28/2024
Categories
express
i18n
middleware
node
Author
sergeyli
Categories
4 categories in total
express
open
i18n
open
middleware
open
node
open
Author
8 person written this
sergeyli
open
A Simple Way to Handle Locale-Specific URLs in Express

Introduction

At TextPixie, as we expanded our AI Translator to support multiple languages, we needed a straightforward internationalization solution that would work with our existing Express-based backend, which doesnโ€™t have built-in i18n support.

While we considered using i18next, we found that it offered much more than we needed and would complicate our backend. Instead, we decided to build a custom solution that focused on the two key requirements for our project:

  1. Setting up locale-specific URLs.
  2. Managing strings in Google Sheets and loading them onto pages based on the locale in the URL.

In this article, Iโ€™ll walk you through how we implemented locale-specific URLs using a simple Express middleware. In a follow-up article, Iโ€™ll dive into how we manage strings in Google Sheets and load them onto pages based on the locale in the URL.

The Problem

When we started expanding our AI Translator, we knew that to make the app truly multilingual, we needed clean, accessible URLs for each supported language. Ideally, our URLs would look something like this:

Our initial approach involved defining routes in Express like this:

app.get('/:lang/', homepageHandler);
app.get('/', defaultHomepageHandler);
app.get('/:lang/image-translator', imageTranslatorHandler);
app.get('/image-translator', defaultImageTranslatorHandler);
Enter fullscreen mode Exit fullscreen mode

However, this method quickly led to two significant issues:

  1. Route Conflicts: The /:lang/ route could unintentionally match URLs meant for other pages, such as /image-translator, leading to incorrect page rendering.
  2. Code Duplication: We had to define multiple routes for each page to handle different languages, which resulted in repetitive and hard-to-maintain code.

Our Middleware Solution

To overcome these challenges, we developed a simple Express middleware function:

function extractLocale(req, res, next) {
    const pathParts = req.path.split("/").filter(Boolean);
    const firstDir = pathParts[0];
    if (checkLocalsExisted(firstDir)) {
        req.lang = firstDir;
        req.url = req.url.replace(`/${firstDir}`, "");
    } else {
        req.lang = "en";
    }
    next();
}
Enter fullscreen mode Exit fullscreen mode

This middleware does two key things:

  1. Locale Extraction: It checks if the first part of the URL is a valid locale (e.g., โ€œenโ€ or โ€œzh-twโ€).
  2. URL Rewriting: If a valid locale is found, it removes the locale from the URL and stores it in req.lang, allowing the rest of the app to process the request without worrying about the locale prefix.

Implementation

We integrated this middleware into our Express application as follows:

const express = require('express');
const app = express();

app.use(extractLocale);

app.get('/', homeHandler);
app.get('/image-translator', imageTranslatorHandler);
Enter fullscreen mode Exit fullscreen mode

Hereโ€™s how the middleware processes different URLs:

This setup allows us to use a single route definition to handle multiple locales, simplifying our codebase and making it easier to maintain. The middleware ensures that the correct locale is extracted and handled without the need for duplicating routes.

Conclusion

By implementing this simple Express middleware, we were able to create a clean and efficient solution for handling locale-specific URLs in our web app. This approach helped us avoid route conflicts, reduce code duplication, and streamline our internationalization process.

In a follow-up article, Iโ€™ll dive into how we manage strings in Google Sheets and load them onto pages based on the locale in the URL. This second step is crucial for ensuring that the right content is displayed to users based on their language preference.

If youโ€™re interested in seeing this solution in action, check out TextPixie AI Translator to experience how we handle multilingual content.


This article was originally published at TextPixie Blog.

i18n Article's
30 articles in total
Favicon
Integration for FormatJS/react-intl: Automated Translations with doloc
Favicon
Introducing date-formatter-i18n: Simplify i18n for Dates in JavaScript
Favicon
Implementing i18n in Next.js - A Complete Guide to next-intl with App Router
Favicon
Integration for Angular: Automated Translations with doloc
Favicon
I18n vue
Favicon
Automating i18n Localization with AI: The Prismy Approach
Favicon
Integrating and storing the selected user language into the database in a full-stack application on "Angular" and "NestJS"
Favicon
๐ŸŽ„ Instant Local Translation with Chrome ๐ŸŒ
Favicon
ICU vs. i18next: Choosing the Right Format for Your Localization Needs
Favicon
LiveCodes Gets a Fresh Look, and Goes Multilingual!
Favicon
A Modern Approach to Software Localization (2024)
Favicon
Pseudolocalization in Phoenix with gettext_pseudolocalize
Favicon
Launching YAMLFish, a simple translations management tool
Favicon
Mastering RTL with One Line of CSS (No Libraries Needed!) ๐Ÿš€
Favicon
Auto-Detect RTL in React with TypeScript! ๐ŸŒ
Favicon
Is Your CSS Logical?
Favicon
Automation and branches- Using YAMLFish to easily manage I18n translations in your project
Favicon
The basics - Using YAMLFish to easily manage I18n translations in your project
Favicon
App Localization with doloc
Favicon
Software Localization Checklist
Favicon
Maneira simples de adicionar suporte a i18n no Rust com exemplos e testes
Favicon
Manera simple de agregar soporte i18n en Rust con ejemplos y pruebas
Favicon
Simple way to make i18n support in Rust with with examples and tests
Favicon
Reliable date formatting in Next.js
Favicon
Even a mouse can do i18n
Favicon
A Simple Way to Handle Locale-Specific URLs in Express
Favicon
Wagtail programmatically create page translation
Favicon
I18n Localization for Nuxt.js ! Implement multi-language support to website.
Favicon
Simplify Localization
Favicon
Comparing Language Detection Libraries (& API) Using Java/ColdFusion/CFML

Featured ones: