{"id":17550,"library":"connect-locale","title":"Connect Locale Middleware","description":"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.","status":"maintenance","version":"1.3.3","language":"javascript","source_language":"en","source_url":"https://github.com/intesso/connect-locale","tags":["javascript","locale","express","connect","locale-detection","i18n","i18n-locale"],"install":[{"cmd":"npm install connect-locale","lang":"bash","label":"npm"},{"cmd":"yarn add connect-locale","lang":"bash","label":"yarn"},{"cmd":"pnpm add connect-locale","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required for the 'cookie' locale detection and storage strategies to ensure cookies are parsed and available on the request object.","package":"cookie-parser","optional":true}],"imports":[{"note":"connect-locale is a CommonJS module. Direct ESM `import` statements will fail without a transpilation step or a CommonJS wrapper.","wrong":"import Locale from 'connect-locale';","symbol":"Locale","correct":"const Locale = require('connect-locale');"},{"note":"The module exports a single function as its default. Destructuring `Locale` from the `require` result will yield `undefined`.","wrong":"const { Locale } = require('connect-locale');\napp.use(Locale(options));","symbol":"Locale","correct":"const Locale = require('connect-locale');\napp.use(Locale(options));"},{"note":"The primary interaction is calling the imported `Locale` function with an options object to configure the middleware.","symbol":"Locale Options","correct":"app.use(Locale({\n  locales: ['en', 'de'],\n  getLocaleFrom: ['path', 'cookie', 'accept-language']\n}));"}],"quickstart":{"code":"const express = require('express');\nconst cookieParser = require('cookie-parser');\nconst Locale = require('connect-locale');\n\nconst app = express();\nconst PORT = process.env.PORT || 3000;\n\n// Important: cookie-parser must be loaded BEFORE connect-locale if using cookie strategy\napp.use(cookieParser());\n\napp.use(Locale({\n    locales: ['en-US', 'en-GB', 'de', 'fr'],\n    getLocaleFrom: ['path', 'cookie', 'accept-language', 'default'],\n    storeLocaleTo: ['cookie', 'request', 'locals'],\n    default: 'en-US'\n}));\n\napp.get('/:locale/hello', (req, res) => {\n    // Locale is available on req.locale and res.locals.locale\n    const currentLocale = req.locale || res.locals.locale || 'unknown';\n    res.send(`Hello from /${currentLocale}/hello! Requested Locale: ${req.requestedLocale}. Is Preferred: ${req.isPreferredLocale}. Available: ${req.locales.join(', ')}`);\n});\n\napp.get('/set-lang/:lang', (req, res) => {\n    // Simulate setting a cookie directly for demonstration, though connect-locale would do this\n    // in a real scenario if 'cookie' is in storeLocaleTo\n    res.cookie('locale', req.params.lang);\n    res.redirect('/');\n});\n\napp.get('/', (req, res) => {\n  const currentLocale = req.locale || res.locals.locale || 'en-US';\n  res.send(`Welcome! Detected locale: ${currentLocale}. Try visiting /de/hello or /set-lang/fr and refresh.`);\n})\n\napp.listen(PORT, () => {\n    console.log(`Server listening on http://localhost:${PORT}`);\n    console.log('Try:');\n    console.log(`  http://localhost:${PORT}/en-GB/hello`);\n    console.log(`  http://localhost:${PORT}/de/hello`);\n    console.log(`  http://localhost:${PORT}/`);\n    console.log(`  http://localhost:${PORT}/set-lang/fr (then refresh /)`);\n});","lang":"javascript","description":"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."},"warnings":[{"fix":"Ensure `app.use(cookieParser())` is called before `app.use(Locale(options))`.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Use `const Locale = require('connect-locale');` for CommonJS environments or configure your build system to handle CJS imports in ESM projects.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Review the source code for potential vulnerabilities or consider alternative actively maintained libraries if long-term support and modern features are critical.","message":"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.","severity":"gotcha","affected_versions":"<=1.3.3"},{"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.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"fix":"Ensure `Locale` middleware is called with a valid options object, e.g., `app.use(Locale({ locales: ['en'], getLocaleFrom: ['default'] }))`.","cause":"`connect-locale` was initialized without an options object or with an invalid one, leading to internal errors when accessing configuration.","error":"TypeError: Cannot read properties of undefined (reading 'locale') at Object.Locale (node_modules/connect-locale/index.js:XX:YY)"},{"fix":"Install `cookie-parser` (`npm install cookie-parser`) and ensure `app.use(cookieParser())` is called before `app.use(Locale(options))`.","cause":"The 'cookie' strategy was enabled in `getLocaleFrom` or `storeLocaleTo`, but `cookie-parser` middleware was not installed or not registered before `connect-locale`.","error":"TypeError: req.cookies is undefined"},{"fix":"Change the import statement to `const Locale = require('connect-locale');`.","cause":"Attempting to use `import Locale from 'connect-locale';` in a CommonJS-only Node.js project or script.","error":"SyntaxError: Cannot use import statement outside a module"},{"fix":"Ensure you are using `const Locale = require('connect-locale');` and then correctly invoking it as `app.use(Locale(options));`.","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`.","error":"TypeError: app.use() requires middleware functions but got a 'undefined'"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}