mashpie / i18n-node

Lightweight simple translation module for node.js / express.js with dynamic json storage. Uses common __('...') syntax in app and templates.
MIT License
3.09k stars 421 forks source link

How to set source for lang param ? #459

Closed golubvladimir closed 3 years ago

golubvladimir commented 3 years ago

The lang can get from cookie, header or query param.

How to set this ?

mashpie commented 3 years ago

with i18n.init as middleware, each incoming request gets processed on the following order:

1) accept-language header is used to determine browser language 2) if a cookie is configured and sent within request, choose that given language instead 3) if a queryParameter is configured and and sent with request, choose that language instead

Config options excerpt from readme:

i18n.configure({
  // sets a custom header name to read the language preference from - accept-language header by default
  header: 'accept-language',

  // sets a custom cookie name to parse locale settings from - defaults to NULL
  cookie: 'yourcookiename',

  // query parameter to switch locale (ie. /home?lang=ch) - defaults to NULL
  queryParameter: 'lang'
})

Still, this is just the default behaviour out-of-the-box. You might implement any custom logic for language guessing and set the resulting locale for current request by:

const guessRequestLanguage = (req) => {
  // your logic to fetch current users language
  return 'ru'
}

app.use((req, res, next) => {
  i18n.setLocale(req, guessRequestLanguage(req))
  next()
})