Angular 12+ : getting errors after applying ssr steps

896 Views Asked by At

I have existing angular project. I need to apply ssr on my existing angular project. I am following this

  1. ng add @nguniversal/express-engine this command works as expected.

  2. npm run dev:ssr after running this command, and opening browser on given link, I am getting following errors

    Could not find translation file: ../../assets/translate/Pages/header/en.json

    Could not find translation file: ../../assets/translate/Pages/footer/en.json

    Could not find translation file: ../../assets/translate/Pages/home/en.json

    ERROR ReferenceError: $ is not defined at HeaderComponent.ngOnInit (mypro\dist\pro\server\main.js:228895:9) ....

    ERROR ReferenceError: FormData is not defined at HomeComponent.getUpcomingEvents (mypro\dist\pro\server\main.js:229576:29) ....

    ERROR ReferenceError: localStorage is not defined at AuthService.isLoggedIn (mypro\dist\pro\server\main.js:240521:9) ....

    1 rules skipped due to selector errors: .custom-file-input:lang(en)~.custom-file-label -> unmatched pseudo-class :lang

    1 rules skipped due to selector errors: .custom-file-input:lang(en)~.custom-file-label -> unmatched pseudo-class :lang

I have tried different ways but getting same errors each time. I am not getting what should I do to apply SSR on existing project. If I create new angular project and apply same steps it works but it does not works on existing project.

How should I remove these errors?

Please help and guide.

2

There are 2 best solutions below

1
On

assets: it sounds like you are using relative paths to retrieve translation files, give a try to absolute paths

$ is more likely due to JQuery usage (that's a good opportunity to get rid of it)

localstorage/FormData: with SSR your app is rendered in a node environment, without a browser. The Web Storage/FormData API isn't available outside of a browser. You find related solutions on Google for localstorage depending on your usage (as there is no code in the question). For Form data:

Install form-data via npm
npm install form-data

then import form-data to your component or service
import * as FormData from 'form-data';
0
On

You can give this article a try: Angular Sevrer Side Rendering

It explains it in more detail and using the ng add command instead of npm commands