0

I am building an Express app for personal use but I want it to support multiple languages. I'm using the i18-node for english (en) and spanish (es) and had written two routes, as follow:

function setLanguage (req, res, next) {
  const locales = i18n.getLocales()
  const { lang } = req.params

  if (locales.includes(lang)) {
    req.setLocale(lang)
    return next()
  }
  return next(new Error('Page not found'))
}

app.get('/', setLanguage, (req, res) => {
  // Renders the home with 'es' as default locale
  res.render('index')
})

app.get('/:lang', setLanguage, (req, res) => {
  // Renders the same view with 'es' or 'en' locale
  res.render('index')
})

If I visit localhost:3000/es or localhost:3000/en it works. If I visit localhost:3000/thisdoesnotexist it shows me the not found page, but if i visit localhost:3000/ it also shows me the not found.

So the question is, how can I set a multilanguage app with a custom not found page?

David Daza
  • 11
  • 2
  • you have to choose a default lang at first. than I think you can set its cookie for previous visits to check the new request's locale from req headers. And one more option is you can provide multilang selection on your not found page so that users can change manually – scetiner Jun 06 '18 at 14:22
  • The default language is set in the i18n configuration. I have cookies in my mind but, as you said, it needs a previous visit from the user. I'm going to take a look to the `req.headers`. Thanks :) – David Daza Jun 06 '18 at 14:38

0 Answers0