Creating Search Engine-Friendly Internationalized Apps with Angular Universal and Transloco šŸŒ

Shahar Kazaz
3 min readSep 12, 2019

--

In this article, I will show you how easily we can add internalization (i18n) support to Angular SSR using the next generation Angular internalization library Transloco. Letā€™s get started.

First, letā€™s create a brand new Angular CLI project:

npx @angular/cli new transloco-ssr

Now, add SSR support by using @nguniversal/express-engine schematics:

ng add @nguniversal/express-engine --clientProject <PROJECT-NAME>

Add Transloco to your project by using schematics:

ng add @ngneat/transloco

Choose your supported languages, and answer Yes for the SSR question. Now you can see that it created the translation files, the loader, and added everything it needs to the AppModule.

When using Angular SSR, we need to change our loader base path to be absolute instead of relative, for it to work. This is already done for you.

The only thing you need to do is modify the new baseUrl property in each one of the environment files based on your application:

Now letā€™s add a new key to our translation files:

{
"title": "Angular SSR with Transloco english"
}

And letā€™s use it in our template:

<ng-template transloco let-t>
{{ t.title }}
</ng-template>

Letā€™s build our application for production using the following commands:

npm run build:ssr
npm run server:ssr

Open your browser and navigate to http://localhost:4000 and Viola! We did it!

Letā€™s see the source HTML file:

We have got a working application with SSR and internalization (i18n) support in 5 minutes.

Bonus

We can use the accept-language header to set the preferred user language automatically. The Accept-Language request HTTP header advertises which languages the client can understand, and which locale variant is preferred.

import { Component, Inject, Optional } from '@angular/core';
import { Request } from 'express';
import { REQUEST } from '@nguniversal/express-engine/tokens';
import { TranslocoService } from '@ngneat/transloco';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(@Optional() @Inject(REQUEST) private request: Request,
private translocoService: TranslocoService) {
if (request.headers) {
translocoService.setActiveLang(
normalize(request.headers['accept-language'])
);
}
}
}

The accept-language headers return the following string:

'accept-language': 
'en-US,en;q=0.9,he;q=0.8,ru;q=0.7,fr;q=0.6,pt;q=0.5'

The normalize function should be your implementation since you need to transform it into the language pattern in your project.

Once you have the language just set it as active.

If you liked this post, please šŸ‘šŸ» and share it!

--

--

Shahar Kazaz

Iā€™m a Frontend Architect who is passionate about coding & web development.