I'm using the nestjs-i18n package (nestjs-i18n) in my NestJS project, and I've noticed that when using i18n within a service like this:
import { Injectable } from '@nestjs/common';
import { I18nContext, I18nService } from 'nestjs-i18n';
@Injectable()
export class AppService {
constructor(private readonly i18nService: I18nService) {}
// I send 'x-lang=en-US' in the header
getHello() {
const message1 = this.i18nService.t('messages.hello'); // Returns fallback language (vi-VN)
const message2 = this.i18nService.t('messages.hello', {
lang: I18nContext.current().lang, // Returns 'en-US' (correct)
});
const message3 = I18nContext.current().t('messages.hello'); // Returns 'en-US' (correct)
return { message1, message2, message3 };
/*{
"message1": "Xin Chào",
"message2": "Hello",
"message3": "Hello"
}*/
}
}
I always have to add lang: I18nContext.current().lang to get the correct language for the current request. Why doesn't it automatically detect the appropriate language for the current request if I don't pass lang:? And here's how I've configured my AppModule:
import { Module } from '@nestjs/common';
// ... other imports
@Module({
imports: [
// ... other imports
I18nModule.forRootAsync({
useFactory: (configService: ConfigService) => ({
fallbackLanguage: configService.getOrThrow('FALLBACK_LANGUAGE'),
loaderOptions: {
path: join(__dirname, '/i18n/'),
watch: true,
},
}),
resolvers: [
new QueryResolver(['lang', 'l']),
new HeaderResolver(['x-lang', 'lang']),
new CookieResolver(),
AcceptLanguageResolver,
],
inject: [ConfigService],
}),
],
// ...
})
export class AppModule {}
I'd appreciate any insights into why this behavior occurs and how I can make the language detection more seamless. Thank you!