Address
Darbhanga, Bihar 846004

 

Angular Universal : server side rendering for better SEO

Server-Side Rendering the Angular application has the following advantages:

  1. SSR helps with Search Engine Optimization. Search engines can parse the page since it is rendered on the server.
  2. Social media platforms like Facebook and Twitter can show a preview of the site when shared.
  3. Once a webpage is rendered on the server, you can cache it and serve it much faster.

To implement server side rendering in Angular application. Angular Universal package is used with the angular application.

Getting started with Angular Universal

Step 1 – Add @nguniversal

From your app directory open a terminal and run the following command:

ng add @nguniversal/express-engine --clientProject YourProjectName 
This command will install the required packages and it will add and update all required files to implement server-side rendering in angular application.
CREATE src/main.server.ts
CREATE src/app/app.server.module.ts
CREATE src/tsconfig.server.json
CREATE server.ts

UPDATE package.json
UPDATE angular.json
UPDATE src/main.ts
UPDATE src/app/app.module.ts
UPDATE tsconfig.json

Step 2 – Building and Serving the App

run the following commands:

npm run build:ssr
npm run serve:ssr

This will serve the angular application with server-side rendered pages on http://localhost:4000 address

npm run build:ssr : This command compiles and create dist folder and in that folder there were 2 folders /browser and /server, normal build and server build.

dist
-browser
-server

npm run serve:ssr : This command serve /server folder only, but when any request is made from browser, it serve template and other static files from /browser folder.

Things to remember:

Since a Universal application runs on the server and not in a browser, there are a few things you need to watch out for in your application code:

  • Check your use of browser-specific objects, such as window, document, or location. These don’t exist on the server.
  • By importing the functions isPlatformBrowser and isPlatformServerfrom @angular/common, injecting the PLATFORM_ID token into your component, and running the imported functions to see whether you’re on the server or the browser.