Connect Locale Middleware

raw JSON →
1.3.3 verified Thu Apr 23 auth: no javascript maintenance

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.

error TypeError: Cannot read properties of undefined (reading 'locale') at Object.Locale (node_modules/connect-locale/index.js:XX:YY)
cause `connect-locale` was initialized without an options object or with an invalid one, leading to internal errors when accessing configuration.
fix
Ensure Locale middleware is called with a valid options object, e.g., app.use(Locale({ locales: ['en'], getLocaleFrom: ['default'] })).
error TypeError: req.cookies is undefined
cause The 'cookie' strategy was enabled in `getLocaleFrom` or `storeLocaleTo`, but `cookie-parser` middleware was not installed or not registered before `connect-locale`.
fix
Install 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
cause Attempting to use `import Locale from 'connect-locale';` in a CommonJS-only Node.js project or script.
fix
Change the import statement to const Locale = require('connect-locale');.
error TypeError: app.use() requires middleware functions but got a 'undefined'
cause This typically happens if `connect-locale` is improperly imported (e.g., `const { Locale } = require('connect-locale');` expecting named exports when it's a default export) or if the `Locale` function itself is not invoked before being passed to `app.use`.
fix
Ensure you are using const Locale = require('connect-locale'); and then correctly invoking it as app.use(Locale(options));.
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.
fix Ensure `app.use(cookieParser())` is called before `app.use(Locale(options))`.
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.
fix Use `const Locale = require('connect-locale');` for CommonJS environments or configure your build system to handle CJS imports in ESM projects.
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.
fix Review the source code for potential vulnerabilities or consider alternative actively maintained libraries if long-term support and modern features are critical.
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.
fix Adjust your application's routing to match the expected URL structure for the 'path' strategy, or choose other `getLocaleFrom` strategies more aligned with your URL design.
npm install connect-locale
yarn add connect-locale
pnpm add connect-locale

This quickstart demonstrates basic integration of connect-locale with Express. It configures locale detection from path, cookies, and the Accept-Language header, storing the result in cookies, the request object, and `res.locals`. It includes the necessary `cookie-parser` middleware and shows how to access the detected locale within a route handler.

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 /)`);
});