florrain / locale

Browser locale negotiation for node.js
MIT License
257 stars 36 forks source link

Not falling back gracefully #34

Closed StevenLangbroek closed 8 years ago

StevenLangbroek commented 8 years ago

I have a client who's launching in 1 market at a time. I read "available locales" by looking for subdirectories in the 'locales' folder. Right now, there's 1 locale in there (de), which results in this availability array: [ 'de' ]. I then initialize locale like so:

export default (app) => {
  // Read available locales from filesystem (subdirectories of '/locales').
  app.locals.availableLocales = getAvailableLocales();

  // Initialialise in-memory cache.
  app.locals.localesCache = {};

  app.use(locale(app.locals.availableLocales));
};

If someone who doesn't have de in their Accept-Language header (like my client), it tries to fall back to en_US... Is this expected behavior, considering the available locales I passed in? It seems weird it just moves on with the user's first locale.

I catch it for now, but it's a bit of a hack imho:

export default (req, res) => {
  const { availableLocales } = req.app.locals;
  let locale = (req.settings.locale || req.locale);
  if (availableLocales.indexOf(locale) === -1) locale = availableLocales[0];
  req.settings.locale = locale;
  res.redirect(locale);
};

Would love to hear your input.

rhagigi commented 8 years ago

Check the value of "process.env.LANG" -- in many cases (my mac for example), the LANG environment variable is set to en_us or something. If it's not set hte code still defaults to 'en-US'. I'd rather make it default to the first supported lang imo, but that'd be a breaking change.

rhagigi commented 8 years ago

As soon as https://github.com/jed/locale/pull/20 is merged you can set an instance default

florrain commented 8 years ago

Released version 0.1.0 that includes the fix for this.