vijay s
vijay s

Reputation: 417

How to setup the middleware Service in nestJs application in nestjs-i18n package to get accept-language header without error?

Hey In my nestjs application, I have installed the nestjs-i18n npm package of version 10.2.6 . I have configured this I18nModule in the appModule as below :

app.module.ts :

import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { PrismaModule } from './config/database';
import { SessionModule } from './modules/session/session.module';
import {
  I18nModule,
  QueryResolver,
  AcceptLanguageResolver,
  HeaderResolver,
} from 'nestjs-i18n';
import * as path from 'path';
import { I18nMiddleware } from './common/hooks/i18n/i18n.middleware';

@Module({
  imports: [
    PrismaModule,
    SessionModule,
    ConfigModule.forRoot({ isGlobal: true }),
    I18nModule.forRoot({
      fallbackLanguage: 'en',
      fallbacks: {
        'en-CA': 'fr',
        'en-*': 'en',
        'fr-*': 'fr',
        pt: 'pt-BR',
      },
      loaderOptions: {
        path: path.join(__dirname, '/i18n/'),
        watch: true,
      },
      resolvers: [
        {
          use: QueryResolver,
          options: ['lang'],
        },
        new HeaderResolver(['x-content-lang']),
        AcceptLanguageResolver,
      ],
    }),
  ],
  controllers: [],
  providers: [],
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(I18nMiddleware).forRoutes('*');
  }
}

I have also have the json files for multiple languages as below structure :


src Folder
    |
    |-i18n Folder
          |
          |--en Folder
                |
                |--en.json
          | --fr Folder
                |
                | -- fr.json
          | --etc

I have configured it in nest-cli.json as below :

nest-cli.json :

{
  "$schema": "https://json.schemastore.org/nest-cli",
  "collection": "@nestjs/schematics",
  "sourceRoot": "src",
  "compilerOptions": {
    "assets": [
      {
        "include": "i18n/**/*",
        "watchAssets":true
      }
    ]
  }
}

Problem :

I want to use the accept-language header to get the user-preferred language for translating the variables accordingly. So i have decided to implement the middleware to achieve it. But I don't know how to do it in the nestjs-i18n package .Please someone help me do this :

I hereby share the middleware i have written :

i18nMiddleware.ts :

import { Injectable, NestMiddleware } from '@nestjs/common';
import { FastifyRequest, FastifyReply } from 'fastify';

@Injectable()
export class I18nMiddleware implements NestMiddleware {
  constructor() {}
  async use(req: FastifyRequest, res: FastifyReply, next: () => void) {
    const lang = req.headers['accept-language']?.toString();
    console.log('............lang', lang);
    if (lang) {
      **// I want to what to write here to make the language received from the header**
    }
    next();
  }
}

So please help me. Thanks in advance .

Upvotes: 0

Views: 2061

Answers (1)

Oluwatobiloba
Oluwatobiloba

Reputation: 122

nestjs-i18n has a middleware it uses internally,

but it you do want to use yours, you can just add it to your guards,

with

const i18n = I18nContext.current();

Here is a link to where I got that from https://nestjs-i18n.com/guides/guard

Upvotes: 0

Related Questions