express-locale is an Express.js middleware designed to robustly determine the locale identifier for incoming HTTP requests. It supports a configurable priority list of lookup sources, including `accept-language` headers, query parameters, cookies, hostname mappings, and a default fallback. Since version 2.0.0, the package standardizes locale output using hyphen-separated format (e.g., `en-US`), aligning with JavaScript's `Intl` object, while still supporting underscore-formatted input for backward compatibility. The current stable version is 2.0.2. While there isn't a strict rapid release cadence, the project receives maintenance updates. Its key differentiators include a flexible configuration for lookup order, the ability to define custom lookup functions, and a clear distinction between language-only and full locale identifiers, with an optional mapping feature, allowing for precise locale resolution based on application needs.
npm install express-localeVerified import paths — ran on the pinned version, not inferred.
This example demonstrates how to integrate `express-locale` middleware, configure lookup priority, set a default locale, and access the determined locale from `req.locale`.
Update any code that relies on locale identifiers being formatted with underscores. Input with underscores is still supported, but output will be hyphenated.
Upgrade your Express.js application to version 4.x or greater. For Express 3.x compatibility, use `express-locale` version 1.x.
Ensure your Node.js environment is an active LTS or the latest stable release. Older Node.js versions may require using `express-locale` version 1.x.
Install `cookie-parser` and ensure `app.use(cookieParser())` is called before `app.use(createLocaleMiddleware())`. You are also responsible for setting the actual locale cookie.
To map language-only results to a full locale, provide a `map` object in your configuration, e.g., `map: { 'en': 'en-GB', 'fr': 'fr-FR' }`.Use a default import for ESM: `import createLocaleMiddleware from 'express-locale';`. For CJS, assign the module's export directly: `const createLocaleMiddleware = require('express-locale');`.Ensure `app.use(createLocaleMiddleware(options))` is called before any route handlers or other middleware that attempt to access `req.locale`.
Either remove `'hostname'` from the `priority` array if not needed, or provide a `hostname` object in your middleware configuration, e.g., `{ hostname: { 'www.example.com': 'en-US' } }`.