Blog>
Snippets

Localization and Internationalization

Apply middleware to handle localization by detecting the user's language preferences and serving up localized content.
const express = require('express');
const i18n = require('i18n');

// Configuration for i18n
i18n.configure({
    locales:['en', 'es', 'fr'],
    directory: __dirname + '/locales',
    defaultLocale: 'en',
    queryParameter: 'lang',
    cookie: 'locale'
});

const app = express();

// Enable cookies for locale tracking
const cookieParser = require('cookie-parser');
app.use(cookieParser());

// Initialize i18n middleware
app.use(i18n.init);

// Middleware to detect user's language
app.use((req, res, next) => {
    let language = req.query.lang || req.cookies.locale || req.acceptsLanguages(i18n.getLocales()) || i18n.getDefaultLocale();
    i18n.setLocale(req, language);
    next();
});
The code sets up an Express app with the i18n library to handle localization. The i18n configuration defines supported locales, the location of locale dictionaries, a default locale, a query parameter, and cookie name for language preference. The middleware detects the user's language based on query parameters, cookies, or the 'Accept-Language' header, and sets the locale for i18n accordingly.
// Define a route that uses localization
app.get('/', (req, res) => {
    // Send a localized greeting based on detected language
    res.send(req.__('Hello'));
});
This route sends a response with a localized greeting. The localized string is retrieved using the i18n's '__' function, which utilizes the current language preference of the user.
// Start the server
const PORT = 3000;
app.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
});
This code starts the Express server on the specified port and logs a message to the console once it's running.