Closed hejsfj closed 4 years ago
Hey @hejsfj!
I don't know if it is the best way to do it but, I've implemented it this way:
//gatsby-browser.js
exports.onClientEntry = () => {
const userLang = navigator.language.substr(0, 2)
if (userLang !== "pl" && !window.location.pathname.startsWith("/en")) {
window.location.pathname = `/en${window.location.pathname}`
}
}
I use pl
as a default page language. So if browser language is not pl
and the path doesn't start with /en
-> then I know I need to redirect the user to /en+path
.
You can also check this package: https://github.com/i18next/i18next-browser-languageDetector
Good luck :)
Thank you! Yes .onClientEntry is what seems to be the best way to redirect.
@przemuh
I put on the file gatsby-browser.js
, but Gatsby did not accept it. Then I put in the file gatsby-node.js
, and Gatsby warned:
ERROR #11329
Your plugins must export known APIs from their gatsby-node.js.
See https://www.gatsbyjs.org/docs/node-apis/ for the list of Gatsby node APIs.
- Your local gatsby-node.js is using the API "onClientEntry" which is not a known API.
What do you mean by "Gatsby did not accept it"?
What do you mean by "Gatsby did not accept it"?
or help, see: https://nodejs.org/en/docs/inspector
success open and validate gatsby-configs - 0.016s
ERROR
This plugin file is using both CommonJS and ES6 module systems together which we don't support.
You'll need to edit the file to use just one or the other.
plugin: /home/gusbemacbe/GitHub/suru-plus-folders/gatsby-browser.js
This didn't cause a problem in Gatsby v1 so you might want to review the migration doc for this:
https://gatsby.dev/no-mixed-modules
not finished load plugins - 0.120s
This plugin file is using both CommonJS and ES6 module systems together which we don't support.
You'll need to edit the file to use just one or the other.
This is the answer to your problem :) You need to write it in ES6 syntax instead of CommonJS:
export const onClientEntry = () => {
const userLang = navigator.language.substr(0, 2)
if (userLang !== "pl" && !window.location.pathname.startsWith("/en")) {
window.location.pathname = `/en${window.location.pathname}`
}
}
@przemuh
Ah, I misunderstood Gabtsby's warning. I thought it does not accept both.
But unfortunately, even with this code, the site does not detect browser's language and does not change to browser's language. :-/
Hej! I just added this plugin to my Gatsby project which is powered by Prismic. I now wonder what might be the best way to add automated browser language detection and redirection to /de/ /en/ and so on...
What's the best practice to do so?