Ask Your Question
1

What are the steps to configure the middleware Service for accepting the language header in nestJs using the nestjs-i18n package, without encountering any errors?

asked 2021-05-09 11:00:00 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2022-11-05 14:00:00 +0000

pufferfish gravatar image
  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.
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-05-09 11:00:00 +0000

Seen: 8 times

Last updated: Nov 05 '22