Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version
  1. Install the nestjs-i18n package by running the command npm install nestjs-i18n.

  2. Import the I18nModule into the root AppModule and configure it. For example:

import { I18nModule } from 'nestjs-i18n';
import * as path from 'path';

@Module({
  imports: [
    I18nModule.forRoot({
      defaultLanguage: 'en',
      fallbackLanguage: 'en',
      parserOptions: {
        path: path.join(__dirname, '/i18n/'),
        watch: false,
      },
    }),
  ],
})
export class AppModule {}

This sets the default language to English and sets the fallback language to English as well if another language header is not accepted. It also specifies the location of the translation files in the /i18n/ directory.

  1. Setup a middleware layer to accept the language header in the main.ts file. For example:
import { I18nMiddleware } from 'nestjs-i18n';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.use(I18nMiddleware);
  await app.listen(3000);
}
bootstrap();

This sets up the middleware to accept the Accept-Language header and check if the language specified in the header is supported by the application.

  1. Create translation files in the specified directory. For example, in /i18n/en.json:
{
  "hello": "Hello World!"
}
  1. Use the TranslateService in your controllers or services to translate text. For example:
import { Controller, Get } from '@nestjs/common';
import { TranslateService } from 'nestjs-i18n';

@Controller()
export class AppController {
  constructor(private readonly translateService: TranslateService) {}

  @Get()
  async getHello(): Promise<string> {
    return await this.translateService.translate('hello');
  }
}

This translates the "hello" key to the value "Hello World!" in the specified language.

  1. Test the application by sending a request with the Accept-Language header set to a supported language. The response should be in the specified language.