Closed kaganAhmetOkan closed 9 months ago
Unfortunately it doesn't look like the request
object from NextJS there is in the format this module is expecting (the type from Node.js)
Hey @kaganAhmetOkan. The Next.js team kinda shows what could be done in these docs, but not really: https://nextjs.org/docs/app/building-your-application/routing/internationalization
Like @dougwilson says, the Next.js request object isn't compatible, but you can just pass the headers to Negotiator. So you could do something like:
const locales = ['en', 'tr'];
let locale = 'en' // your default locale
const languageHeaders = request.headers.get('Accept-Language')
if (languageHeaders) {
locale = new Negotiator({
headers: {'accept-language': languageHeaders},
}).language(locales)
}
Hey @kaganAhmetOkan. The Next.js team kinda shows what could be done in these docs, but not really: https://nextjs.org/docs/app/building-your-application/routing/internationalization
Like @dougwilson says, the Next.js request object isn't compatible, but you can just pass the headers to Negotiator. So you could do something like:
const locales = ['en', 'tr']; let locale = 'en' // your default locale const languageHeaders = request.headers.get('Accept-Language') if (languageHeaders) { locale = new Negotiator({ headers: {'accept-language': languageHeaders}, }).language(locales) }
Hey @jmagrippis, thank you for your help. I had not thought about passing the accept-language header directly.
.language(locales)
returns undefined when there is no available language. So, I've ended up using this block of code for anyone in the future:
const locales = ["en", "tr"];
const defaultLocale = "en";
const languageHeaders = request.headers.get("Accept-Language");
const locale = new Negotiator({ headers: {"accept-language": languageHeaders }}).language(locales);
return locale ?? defaultLocale;
in
middleware.js
:curl -v --header "Accept-Language: tr" localhost:3000
redirects me to/en
regardless of the accept-language header.The whole middleware:
I don't really understand what I'm getting wrong here. Excuse me if I'm missing something very simple.