Implementing multi-language support in an Express.js application involves managing translations and serving the appropriate content based on the user's language preference. Here's a step-by-step guide to help you achieve this:
Install the required packages for handling localization and translations:
bashnpm install i18n express-session
Create a folder structure for your translations. For example:
markdown- /locales
- en.json
- es.json
- fr.json
- /views
- index.ejs
- ...
- app.js
In your app.js
file, set up i18n middleware to handle translations. Import the necessary modules and configure i18n:
javascriptconst express = require('express');
const i18n = require('i18n');
const app = express();
// Set up i18n middleware
i18n.configure({
locales: ['en', 'es', 'fr'],
directory: __dirname + '/locales',
defaultLocale: 'en',
cookie: 'lang',
});
app.use(i18n.init);
Create routes to allow users to switch languages. In this example, we'll use a query parameter to set the language:
javascriptapp.get('/set-language/:lang', (req, res) => {
const lang = req.params.lang;
res.cookie('lang', lang);
res.redirect('back');
});
Create JSON files for each language in the locales
folder. For example, en.json
, es.json
, and fr.json
:
en.json:
json{
"hello": "Hello",
"welcome": "Welcome to our application"
}
es.json:
json{
"hello": "Hello",
"welcome": "Welcome to our application"
}
fr.json:
json{
"hello": "Bonjour",
"welcome": "Bienvenue dans notre application"
}
In your EJS templates or other view engines, use the __
function provided by i18n to display translated content:
ejs<!-- views/index.ejs --> <h1><%= __("hello") %></h1> <p><%= __("welcome") %></p>
Ensure that your application gracefully handles cases where the user's preferred language is not available. You can set a default language in your i18n configuration and provide a fallback:
javascripti18n.configure({
// ...
defaultLocale: 'en',
fallbacks: { 'en-US': 'en' }, // Example fallback for American English
// ...
});
You can enhance language detection by checking the Accept-Language
header or other user preferences. Update your middleware to include language detection logic if needed.
Start your Express.js application:
bashnode app.js
Visit http://localhost:3000
in your browser, and you should see the application with multi-language support.
This is a basic implementation, and you can further enhance it based on your specific requirements.