Internationalization (i18n)
Share:
Nest.js is a popular framework renowned for its modularity and scalability. One integral feature often desired in apps today, due to increased globalization and the need to cater to diverse groups of users, is internationalization (often shortened to i18n). Internationalization allows you to take into account different localizations, currencies, timezones, and more significantly, languages, making your app more user-friendly and accessible to a wider audience. This chapter provides an in-depth guide on how to implement i18n in your Nest.js application, using a movie-themed example to further add a touch of fun and relatablity.
To illustrate the concepts, let's use a scenario where we are building an online movie store where people from different countries can buy movies. We want to tailor our messages and responses to the locale of the user, hence we need internationalization.
To facilitate internationalization in Nest.js, we will be using an npm package called nestjs-i18n
. Start by installing these packages:
$ npm install --save nestjs-i18n
Now, let's start the implementation.
Firstly, import the module in the file that serves as the root or base of your application, typically app.module.ts
.
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { I18nModule, I18nJsonParser } from 'nestjs-i18n';
import path from 'path';
@Module({
imports: [
I18nModule.forRoot({
fallbackLanguage: 'en',
parser: I18nJsonParser,
parserOptions: {
path: path.join(__dirname, '/i18n/'),
}
}),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
In the above code snippet, we imported I18nModule
from nestjs-i18n
and included it in our module imports. We specified English ('en') as our fallback language, this means if the application does not find translations in the user's locale, it would default to English. I18nJsonParser
lets us use JSON files for our translations. parserOptions
defines the path to our translation files which we create in the /i18n/
directory.
Next, let's create some translation files in the i18n/
directory. We'll create two files: en.json
(English) and fr.json
(French).
en.json
:
{
"MOVIE_GREETING": "Welcome to our movie store!",
"FETCH_SUCCESS": "Movies fetched successfully."
}
fr.json
:
{
"MOVIE_GREETING": "Bienvenue dans notre boutique de films!",
"FETCH_SUCCESS": "Films récupérés avec succès."
}
Now that we have setup nestjs-i18n
and have few translations to play with, let's implement i18n in our controller.
import { Controller, Get, UseGuards } from '@nestjs/common';
import { I18nService, I18nRequestScopeService, I18nLang } from 'nestjs-i18n';
import { AppService } from './app.service';
@Controller('movies')
export class AppController {
constructor(
private readonly appService: AppService,
private readonly i18n: I18nService,
private readonly i18nRequestScopeService: I18nRequestScopeService,
) {}
@Get()
async fetchMovies(@I18nLang() lang: string) {
const greeting = await this.i18nRequestScopeService.translate('MOVIE_GREETING');
const fetchDataMessage = await this.i18nRequestScopeService.translate('FETCH_SUCCESS');
const movies = this.appService.getMovies();
return { lang, greeting, fetchDataMessage, movies };
}
}
In this controller, we injected I18nService
and I18nRequestScopeService
. I18nLang()
decorator allows us to fetch the language in request headers. When called this.i18nRequestScopeService.translate()
, based on the language provided in request headers, it would translate the corresponding key.
Now imagine a French user visits our movie store, their 'Accept-Language' header will be 'fr', and this would translate the greeting and fetch data message to French.
Internationalization in Nest.js raises its overall adaptability, making it more user-friendly for global audiences. As your application grows, you could add more languages by writing additional translation JSON files and placing them in the i18n directory.
In conclusion, Nest.js and its accompanying libraries make the handling of internationalization remarkably straightforward. By implementing this feature, your application can cater to a worldwide audience, transforming the user experience for the better.
0 Comment
Sign up or Log in to leave a comment