Struggling with configuring internationalization in NestJS

Currently, I am working on a NestJS project where my lead assigned me the task of returning different errors to the frontend based on the language in the request header. After some research, I decided to use i18n for this purpose. However, when testing it in postman, instead of returning the message, it displayed the variable name. For example, if there is a variable called "test" with the value "HelloWorld" in the JSON file, it would return "test" instead of "HelloWorld".

I have tried looking for solutions and suggestions on previous posts, revisited the documentation, and even copied code from another project with i18n setup by my lead, but I still can't figure out what's missing. Any help would be greatly appreciated.

I am willing to share relevant files from the project for anyone who can identify the issue.

package.json

{
  "name": "nest-experiments",
  "version": "0.0.1",
  "description": "",
  "author": "",
  "private": true,
  "license": "UNLICENSED",
  "scripts": {
    ...
  },
  "dependencies": {
    ...
  },
  "devDependencies": {
    ...
  },
  "jest": {
    ...
  }
}

nest-cli.json

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

app.module.ts The code here may differ slightly from the current documentation as it is based on my lead's project.

import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import {
  AcceptLanguageResolver,
  CookieResolver,
  HeaderResolver,
  I18nJsonLoader,
  I18nModule,
  QueryResolver,
} from 'nestjs-i18n';
import * as path from 'path';

import { AppController } from './app.controller';
import { AppService } from './app.service';
import { PointsModule } from './points/points.module';
import { SlackModule } from './slack/slack.module';
import { UsersModule } from './users/users.module';

@Module({
  imports: [PointsModule, MongooseModule.forRoot('mongodb+srv://sharbelabousabha:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9fada9aca6c7eeafe6acc8a6decbc9fad0dffcf3eaecebfaedafbfb1b4">[email protected]</a>/?retryWrites=true&w=majority'), SlackModule, UsersModule,
    I18nModule.forRoot({
      fallbackLanguage: 'en',
      loaderOptions: {
        path: path.join(__dirname, '/i18n/'),
        watch: true,
      },
      resolvers: [
        { use: QueryResolver, options: ['lang', 'locale', 'l'] },
        new HeaderResolver(['x-custom-lang']),
        AcceptLanguageResolver,
        new CookieResolver(['lang', 'locale', 'l']),
      ],
    })

  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule { }

app.service.ts

import { Injectable } from '@nestjs/common';
import { I18nContext, I18nService } from 'nestjs-i18n';

@Injectable()
export class AppService {
  constructor(private readonly i18n: I18nService) {}
  getHello(): string {
    console.log({ lang:   I18nContext.current().lang })
    return this.i18n.translate('Created.Success');
  }
}

Answer №1

It was discovered that including the name of the JSON file at the beginning is crucial. In this scenario, instead of using Created.Success, it required user.Created.Success

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be causing the countdown timer to speed up unexpectedly?

Currently, I am developing a quiz application. At the moment, I need to implement the following features: Countdown timer Questions Question Choices The countdown timer for each question functions properly as long as the answer button is not clicked or ...

Creating a Typescript type for the react-intl component within a single file

Currently, I'm trying to incorporate the injectIntl component directly in the file instead of using the traditional export default injectIntl(Component). However, I am encountering difficulties when it comes to typing the component. This is a snippet ...

How come my ts-mockito spy isn't delegating method calls properly?

In my code, I have a class named MyPresenter which has a method called doOperation(). This method calls another method on a View class that implements an interface and is passed in as a parameter. Below you can find the implementation of the class, interfa ...

UI and `setState` out of sync

Creating a website with forum-like features, where different forums are displayed using Next.js and include a pagination button for navigating to the next page. Current implementation involves querying data using getServerSideProps on initial page load, f ...

Encountering a cloning error while using React Typescript and React Router DOM when calling props.history.push

When using props.history.push without passing state, everything works perfectly fine. However, when trying to pass data with state, an error occurs. The error message reads: DOMException: Failed to execute 'pushState' on 'History': func ...

Pass an array of objects to an Angular 8 component for rendering

Recently, I started working with Angular 8 and faced an issue while trying to pass an array of objects to my component for displaying it in the UI. parent-component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: ...

Can you reach a screen prior to the stack navigator being established?

I'm diving into the world of React and decided to use Expo for building an app. I went with the TypeScript setup that comes with pre-implemented tabs and navigator by running "expo init newApp". Now, I just need a transition screen to display briefly ...

A Guide to Iterating Through Arrays of Objects Using TypeScript

Currently, I am engrossed in an Angular project where I am fetching an object containing an array of objects from an API. The object being passed to the API as a parameter through my service is called "reportData". Here is an example of the data retrieve ...

A versatile Typescript array serving both as a storage for type information and input parameters

Our API is designed to handle a large amount of data, allowing users to control which properties are returned by using the fields parameter. The API definition looks like this: interface Foo { A?: string; B?: number; C?: boolean; D?: string ...

Intellisense fails to function properly after attempting to import a custom npm package

I've encountered an issue with a custom npm package that I created using storybook. The components function properly in other projects when imported, but the intellisense feature is not working as expected. Interestingly, when I import the same compon ...

Create a custom component that wraps the Material-UI TextField component and includes default

I have been exploring React and had a question regarding wrapping a component like TextField from mui to add new props along with the existing ones. I attempted to do this but am struggling to figure out how to access the other props. Can anyone help me ...

In the en-US locale, the toLocaleDateString function is transforming "00:30" into 24:30

Questioning the Conversion of Time from 00:30 to 24:30 in en-US Locale options = { year: "numeric", day: "numeric", month: "numeric", hour: '2-digit', minute: '2-digit&apo ...

Tips for receiving an array input in a GraphQL resolver

My query variables contain an array of strings that I need to use as the ids parameter inside my resolver. Below is the relevant code snippet. People.resolver.ts import { Resolver, Query, Mutation, Args, } from '@nestjs/graphql'; import { Peopl ...

Implement the fastifySession Middleware within NestJS by incorporating it into the MiddlewareConsumer within the AppModule

I have a Nestjs application running with Fastify. My goal is to implement the fastifySession middleware using the MiddlewareConsumer in Nestjs. Typically, the configuration looks like this: configure(consumer: MiddlewareConsumer) { consumer .appl ...

Using React and TypeScript to create multiple click handlers for different sections within the same div element

I am a beginner in the world of React, Typescript, and coding in general, so I'm not entirely sure if what I'm attempting is even possible. Currently, I have a donut chart with clickable segments sourced from a minimal pie chart found at: https:/ ...

Encountering difficulty creating a new entity in NestJS with TypeORM due to the error message EntityMetadataNotFoundError

Hey, I've been encountering some issues with TypeORM. I'm attempting to add a new entity to my current project and here's what I did: I created a new entity import { Entity, Column, PrimaryGeneratedColumn, JoinColumn, OneToOne } from ' ...

Typescript Error: lib.d.ts file not found

Recently, I experimented with Typescript and utilized the Set data structure in this manner: var myset = new Set<string>(); I was pleasantly surprised that there was no need for additional libraries in Typescript, and the code worked smoothly. Howe ...

Could one potentially assign number literals to the keys of a tuple as a union?

Imagine having a tuple in TypeScript like this: type MyTuple = [string, number]; Now, the goal is to find the union of all numeric keys for this tuple, such as 0 | 1. This can be achieved using the following code snippet: type MyKeys = Exclude<keyof ...

a search-enabled dropdown menu within an Angular input field

I can't seem to get the input box to display in my code below. Can you help me figure out why? component.html <form [formGroup]="formGroup" (validSubmit)="onSubmit()"> <div class="form-group mb-3"> ...

Definition file for Typescript Angular 1.5 component

Encountering a problem with typescript and angular 1.5 - when building, an error pops up saying error TS2339: Property 'component' does not exist on type 'IModule'.. Could it be that I overlooked a definition file containing this proper ...