Connect Locale Middleware
raw JSON →connect-locale is a configurable Express/Connect middleware designed specifically for detecting and storing user locale preferences within web applications. It is not a comprehensive i18n solution for managing resource files, but rather focuses on establishing a flexible strategy for locale identification and persistence. The library allows developers to define a sequence of strategies (e.g., path, cookie, accept-language header) to determine the user's preferred locale and then store it in various locations (e.g., cookie, session, request object, `res.locals`) for subsequent use in other middleware or templating engines. The current stable version is 1.3.3. Given its last update several years ago, it is in maintenance mode, providing a stable, albeit not actively developed, solution for locale detection. Its key differentiators are its highly configurable detection and storage mechanisms, allowing for custom i18n strategies.
Common errors
error TypeError: Cannot read properties of undefined (reading 'locale') at Object.Locale (node_modules/connect-locale/index.js:XX:YY) ↓
Locale middleware is called with a valid options object, e.g., app.use(Locale({ locales: ['en'], getLocaleFrom: ['default'] })). error TypeError: req.cookies is undefined ↓
cookie-parser (npm install cookie-parser) and ensure app.use(cookieParser()) is called before app.use(Locale(options)). error SyntaxError: Cannot use import statement outside a module ↓
const Locale = require('connect-locale');. error TypeError: app.use() requires middleware functions but got a 'undefined' ↓
const Locale = require('connect-locale'); and then correctly invoking it as app.use(Locale(options));. Warnings
gotcha If using the 'cookie' strategy for locale detection or storage, the `cookie-parser` middleware must be registered with Express *before* `connect-locale` to ensure `req.cookies` is populated. ↓
gotcha connect-locale is a CommonJS module. Attempting to `import` it directly in an ESM context will result in a `SyntaxError` unless a transpiler (like Babel or TypeScript) is configured to handle CJS imports. ↓
gotcha The package has not been updated in several years (last published version 1.3.3 six years ago). While functional, it may not receive updates for security vulnerabilities, compatibility with very recent Node.js/Express versions, or new features. ↓
gotcha The 'path' strategy assumes the locale is the first segment of the URL (e.g., `/en/some/path`). If your URL structure is different, this strategy may not work as expected. ↓
Install
npm install connect-locale yarn add connect-locale pnpm add connect-locale Imports
- Locale wrong
import Locale from 'connect-locale';correctconst Locale = require('connect-locale'); - Locale wrong
const { Locale } = require('connect-locale'); app.use(Locale(options));correctconst Locale = require('connect-locale'); app.use(Locale(options)); - Locale Options
app.use(Locale({ locales: ['en', 'de'], getLocaleFrom: ['path', 'cookie', 'accept-language'] }));
Quickstart
const express = require('express');
const cookieParser = require('cookie-parser');
const Locale = require('connect-locale');
const app = express();
const PORT = process.env.PORT || 3000;
// Important: cookie-parser must be loaded BEFORE connect-locale if using cookie strategy
app.use(cookieParser());
app.use(Locale({
locales: ['en-US', 'en-GB', 'de', 'fr'],
getLocaleFrom: ['path', 'cookie', 'accept-language', 'default'],
storeLocaleTo: ['cookie', 'request', 'locals'],
default: 'en-US'
}));
app.get('/:locale/hello', (req, res) => {
// Locale is available on req.locale and res.locals.locale
const currentLocale = req.locale || res.locals.locale || 'unknown';
res.send(`Hello from /${currentLocale}/hello! Requested Locale: ${req.requestedLocale}. Is Preferred: ${req.isPreferredLocale}. Available: ${req.locales.join(', ')}`);
});
app.get('/set-lang/:lang', (req, res) => {
// Simulate setting a cookie directly for demonstration, though connect-locale would do this
// in a real scenario if 'cookie' is in storeLocaleTo
res.cookie('locale', req.params.lang);
res.redirect('/');
});
app.get('/', (req, res) => {
const currentLocale = req.locale || res.locals.locale || 'en-US';
res.send(`Welcome! Detected locale: ${currentLocale}. Try visiting /de/hello or /set-lang/fr and refresh.`);
})
app.listen(PORT, () => {
console.log(`Server listening on http://localhost:${PORT}`);
console.log('Try:');
console.log(` http://localhost:${PORT}/en-GB/hello`);
console.log(` http://localhost:${PORT}/de/hello`);
console.log(` http://localhost:${PORT}/`);
console.log(` http://localhost:${PORT}/set-lang/fr (then refresh /)`);
});