Angular SSR guide
Why we use Angular SSR ?
- Make easy of Search engine optimization (SEO).
- To show first page quickly.
- To improve performance.
Angular Application to Universal Angular application:
- Install the Node Module
ng add @nguniversal/express-engine
2. Now you can run your project using following cmds
npm run build:ssr && npm run serve:ssr
If every thing works fine than you can serve your project in http://localhost:4000
If it fails to run than you might get below errors
> ERROR ReferenceError: localStorage is not defined
> ERROR ReferenceError: window is not defined
> ERROR ReferenceError: gtag is not defined
- ERROR ReferenceError: localStorage is not defined
Install npm install localstorage-polyfill
Add this in server.ts
import ‘localstorage-polyfill’
global[‘localStorage’] = localStorage;
2. ERROR ReferenceError: window is not defined
// Copy the following content
const domino = require('domino');
const fs = require('fs');
const path = require('path');
const template = fs.readFileSync(path.join('.', 'dist/your-project-directory-name', 'index.html')).toString();
const win = domino.createWindow(template);
// tslint:disable-next-line:no-string-literal
global['window'] = win;
// tslint:disable-next-line:no-string-literal
global['document'] = win.document;
// tslint:disable-next-line:no-string-literal
Get Pradeep’s stories in your inbox
Join Medium for free to get updates from this writer.
global['DOMTokenList'] = win.DOMTokenList;
// tslint:disable-next-line:no-string-literal
global['Node'] = win.Node;
// tslint:disable-next-line:no-string-literal
global['Text'] = win.Text;
// tslint:disable-next-line:no-string-literal
global['HTMLElement'] = win.HTMLElement;
// tslint:disable-next-line:no-string-literal
global['navigator'] = win.navigator;
// tslint:disable-next-line:no-string-literal
global['MutationObserver'] = getMockMutationObserver();
function getMockMutationObserver() {
return class {
observe(node, options) {
}
disconnect() {
}
takeRecords() {
return [];
}
};
}
// ……………….end………….
3. ERROR ReferenceError: gtag is not defined
Inject the following service in constructor
@Inject(PLATFORM_ID) private platformId: object
Import missing dependencies
import { Injectable, Inject, PLATFORM_ID } from ‘@angular/core’;
Use the code snippets
if (isPlatformBrowser(this.platformId)) {
// your gtag code is here
}
Now you can re-build again using npm run build:ssr and than npm run serve:ssr.









