Internationalization (i18n) Middleware
In this lesson, you will learn how to detect a user's language preference from request headers and automatically localize your server's responses.
The Core Concept
When a user visits your application, their browser sends an Accept-Language header that lists the languages they prefer (e.g., en-US,en;q=0.9,fr;q=0.8). Instead of writing logic inside every single route handler to check this header, we use Internationalization Middleware. This middleware acts as an interceptor in the request lifecycle: it reads the incoming header, determines the best match against your supported languages, and attaches the localized information to the req object for the rest of your application to use.
Implementation Illustration
By injecting the locale into the request object early in the pipeline, your downstream route handlers can remain "locale-agnostic." They simply look at the property provided by your middleware.
// A simple i18n middleware
const i18nMiddleware = (req, res, next) => {
const acceptLanguage = req.headers['accept-language'];
// Logic to parse the header and match it to your supported languages
// For example, defaulting to 'en' if no match is found
const locale = acceptLanguage?.includes('fr') ? 'fr' : 'en';
// Attach the locale to the request object
req.locale = locale;
next();
};
// Usage in your server
app.use(i18nMiddleware);
app.get('/greet', (req, res) => {
const greetings = {
en: 'Hello!',
fr: 'Bonjour!'
};
res.send(greetings[req.locale]);
});
Why Middleware?
By handling this as middleware, you achieve two things:
- Consistency: Every request is evaluated the same way before it reaches your business logic.
- Cleanliness: Your controllers don't need to parse complex HTTP headers. They just read
req.locale, which is ready and waiting for them. This keeps your request lifecycle predictable and ensures that your application responds naturally to users from different parts of the world.
Key Takeaway: Internationalization middleware encapsulates the complexity of content negotiation, allowing you to pass a standardized locale identifier down the request pipeline to drive localized response generation.