Detect browser language when using `nuxt generate` (in 'universal' mode)
See original GitHub issueVersion
Reproduction link
https://github.com/tex0l/nuxt-i18n-repro-case
Steps to reproduce
Start a static server on a project built using nuxt generate
in 'universal'
mode. The test case provided does exactly that with an nginx server started with the result of the nuxt generate
with docker.
What is expected ?
The detectBrowserLanguage
feature should be used, just as in 'spa'
mode.
What is actually happening?
The detectBrowserLanguage
feature isn’t used, considering it should be done server-side, but since there’s no server, it doesn’t word at all.
Additional comments?
The problem lies in the fact that it is done in a middleware: https://github.com/nuxt-community/nuxt-i18n/blob/master/src/templates/middleware.js#L101
When using nuxt generate
, the middlewares are executed at build-time, not at run-time.
I worked around the issue by putting this in my layout’s mounted
method:
if (process.browser) {
if (this.$cookie.get('i18n_redirected') !== '1') {
const lang = navigator.language.toLocaleLowerCase().substring(0, 2)
this.$cookie.set('i18n_redirected', '1')
this.$router.push(this.switchLocalePath(lang))
}
}
}
<div align="right">This bug report is available on Nuxt community (#c185)</div>Issue Analytics
- State:
- Created 5 years ago
- Reactions:12
- Comments:9
Top GitHub Comments
While the above solution might work in specific cases, the middleware is doing a lot more in the meantime. Imo this issue should be fixed in nuxt-i18n, instead of just mentioning it in the documentation.
@rchl you are right, browser detection works, but it was really strange. When I’ve deployed it on Netlify it didn’t work, but on Firebase hosting everything works properly