Creating applications that cater to a global audience requires support for multiple languages and regional preferences. This is where internationalization (i18n) and localization (l10n) come into play. In Express.js, these processes are made easier with middleware and libraries that help in handling translations, date formatting, currency, and other locale-specific settings.
Together, i18n and l10n enable applications to deliver content that feels native to users from different parts of the world.
In Express.js, there are several libraries available to assist with i18n, one of the most popular being i18n
. This library provides an easy way to implement language translations and locale management.
npm install i18n
const express = require('express');
const i18n = require('i18n');
const app = express();
i18n.configure({
locales: ['en', 'es', 'fr'], // Supported languages (e.g., English, Spanish, French)
directory: __dirname + '/locales', // Directory where translation files are stored
defaultLocale: 'en', // Default language
queryParameter: 'lang', // Language switch parameter in URL
autoReload: true, // Automatically reload changes to locale files
});
app.use(i18n.init);
app.get('/', (req, res) => {
res.send(res.__('welcome'));
});
app.listen(3000, () => console.log('Server running on port 3000'));
In this setup:
locales
: Lists supported languages.directory
: Specifies where translation files are stored (e.g., /locales/en.json
, /locales/es.json
).defaultLocale
: Sets a fallback language if the requested language is unavailable.queryParameter
: Allows users to switch languages via the query string.Once configured, create JSON files for each locale in the /locales
directory. These files will contain key-value pairs of translation texts.
/locales/en.json
{
"welcome": "Welcome to our website!",
"greeting": "Hello, how can we help you today?"
}
/locales/es.json
{
"welcome": "¡Bienvenido a nuestro sitio web!",
"greeting": "Hola, ¿cómo podemos ayudarte hoy?"
}
Use res.__()
to retrieve the translation for the current locale.
app.get('/', (req, res) => {
res.send(res.__('welcome')); // Will display 'Welcome to our website!' for 'en' locale
});
To view the application in Spanish, navigate to http://localhost:3000/?lang=es
. The output changes based on the selected language.
For content that may vary depending on the language, use res.__()
directly in dynamic responses.
app.get('/greeting', (req, res) => {
const message = res.__('greeting');
res.send(`${message}
`);
});
To handle multiple locales dynamically:
i18n.configure
.
app.use((req, res, next) => {
const lang = req.headers['accept-language']?.split(',')[0] || 'en';
i18n.setLocale(req, lang);
next();
});
The accept-language
header is often set by browsers and indicates the user’s preferred language.
To format dates, numbers, and currencies, use Intl
or external libraries like moment.js
or luxon
for date localization.
Intl
for Date Formatting
const date = new Date();
const formattedDate = new Intl.DateTimeFormat('fr-FR').format(date);
console.log(formattedDate); // Example: '10/11/2024' in French format
const price = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(500);
console.log(price); // Output: $500.00
If using a template engine (e.g., Pug, EJS), pass translations directly to the view.
app.set('view engine', 'ejs');
app.get('/', (req, res) => {
res.render('index', { title: res.__('welcome') });
});
index.ejs
Example
<%= title %>
<%= title %>
welcome_message
) for translations rather than raw text, which aids in readability and maintenance.Internationalization and localization are essential for building user-friendly applications that cater to a global audience. By leveraging tools like i18n with Express.js, you can efficiently manage translations, handle multiple locales, and format region-specific data like dates and currency. Happy Coding!❤️