Server Side Rendering In Angular

Server Side Rendering In Angular

In this article, we learn how to use Angular Universal to implement server-side rendering. Before transmitting the pages to the browser, a method called server-side rendering, or SSR, renders them on the server. We will discover what Angular Universal is and why server-side rendering is essential. Later, we'll demonstrate how to build a sample server-side rendered Angular universal app. We also go over some very crucial information that you should understand before beginning to use Angular Universal for server-side rendering.

What is Angular Universal

Before transmitting the requested URL to the user's browser, Angular Universal renders the HTML view on the server. As a result, the app will load more quickly and, more crucially, be more search engine friendly.

Why is Server Side rendering required?

The Angular applications are one-page applications. There is a lot of javascript code in them. These Javascript scripts execute in the client's browser and instantly produce an HTML view. When a user switches between pages in the app, the app doesn't make any requests to the server. The page is rendered entirely by the browser. Only data and static resources, such as photos, are requested by the app from the backend. As a result, the user can use the application relatively quickly.

However, users are drawn to the website by search engines. Each page receives a rank based on a variety of criteria. The two main ranking factors are speed and content. SPA frameworks like Angular suffer from this.

Speed

The Angular apps load slowly at first for the following reasons:

  1. It has a lot of JavaScript files to download.
  2. Render the HTML to the view while running the JavaScript.

Content

The search engines must run JavaScript in order to display the material. Google does a decent job at interpreting the content and running the JavaScript, but you can't always rely on it to be accurate. Other search engines, such as Bing and others, are likewise unable to process it. The content won't be visible to social media crawlers like Facebook and Twitter because they don't run JavaScript.

By producing the content on the server and sending the user static HTML, we can fix the aforementioned issues.

What is Server-Side Rendering

The process is known as "Server-Side Rendering," or SSR involves running JavaScript on the server to create an HTML file that is then sent to the client.

For instance, the server finds index.html when it receives a request for a specific page. The server now delivers it to a renderer process rather than providing it to the browser. The Renderer creates HTML while running the Angular Framework (much like it would in a browser). If necessary to obtain the data, it also sends HTTP requests to the backend server. The server then sends the browser the HTML it produced.

The user can now see the HTML thanks to the browser. The browser has not yet downloaded Angular, thus the page will not be affected by mouse or keyboard events at this time. The page isn't interactive yet.

The Angular framework is starting to download in the browser. After Angular bootstraps and loads, it begins to record user events. It becomes interactive on the page. From this point on, Angular takes over and all subsequent client-side navigation occurs.

Server Side rendering Vs Client-Side Rendering

The contrast between client-side rendering and server-side rendering is shown in the following table.

Sr.NoClient-Side RenderingServer Side Rendering
1The user sends the requests for a pageThe user sends the requests for a page
2The server locates the index.html and sends it to the userThe server locates the index.html and sends it to the Renderer Process running in Server
3Renderer prepares the initial page, by executing the Angular Framework and sends it to the browser
4The Browser displays the blank page, but there is no content thereThe browser shows the initial page to the user. The page may be non-interactive at this time.
5The browser downloads the CSS & JavaScriptThe browser downloads the CSS & Javascript
6The browser executes Angular Framework (JavaScript) & Renders the pageThe browser executes Angular Framework (JavaScript)
7The user sees the Interactive PageThe page becomes interactive.


Content and SSR

There is no need for search engines to run the javascript because the server creates the content. The HTML is visible to social media crawlers as well.

Speed and SSR

Does it address the speed issue? The quick response is "no"

SSR implementation alone won't make a site faster. mainly because all you are doing is shifting the rendering from the browser to the server. In reality, a busy server may cause your site to load slowly.

However, it will enhance the initial FCP or paint.

However, when you cache the produced response, you experience excellent speed. By serving the user a cached answer, the rendering step is cut off, and the user receives the HTML immediately. Only the SSR allows for this.

Example

Using the Angular CLI, create a new Angular project.

ng new ssr

View the page source by doing a right-click anywhere on the browser windows. You'll notice there isn't any material. When they explore your website, search engines will detect this.

<html lang="en">
<head>
  <meta charset="utf-8"></meta>
  <title>Ssr</title>
  <base href="/"></base>
  <meta content="width=device-width, initial-scale=1" name="viewport"></meta>
  <link href="favicon.ico" rel="icon" type="image/x-icon"></link>
</head>
<body>
  <app-root></app-root>
<script src="runtime.js" type="module"></script><script src="polyfills.js" type="module"></script><script src="styles.js" type="module"></script><script src="vendor.js" type="module"></script><script src="main.js" type="module"></script></body>
</html>

Adding Angular Universal

Run the following command to add Angular Universal to the project mentioned above. The express-engine will be added to the project. Under the flag --client project, you must specify the project's name. The project's name is the one you enter when you use ng new <projectName> to create the project.

ng add @nguniversal/express-engine --clientProject ssr

The angular.json file under the projects node contains the project name.

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "ssr": {                             ====> Name of the project
      "projectType": "application",
      "schematics": {},

You can now launch the project by executing the next command.

As you can see from the below image, compiling it will take some time.


Compiling Angular Universal Application


Instead of using port 4200, the app will use port 4000. Now that you have right-clicked, you may view the content by looking at the source. When crawlers visit your site, they see this.

Notes

No Hash Location Strategy

You should switch to PathLocationStrategy if you are still using HashLocationStrategy (URL looks like http://localhost:4200/#/product). They are incompatible with Universal Apps.

Browser API Does not work

Only the browser supports objects like a window, location, document, etc. They are absent from the server. For those tasks, you can use Document or Location.

The nativeElement and ElementRef methods for modifying DOM elements will not function on the server. You may use the Renderer2

Find out where you are running the server or browser

Sometimes it's important to determine if the code is running in the browser or the server. You might want to use a browser API, for instance, but this won't work on the server and could lead to a problem. The @angular/common package of the Angular has the isPlatformBrowser & isPlatformServer functions. Using the injection token for PLATFORM ID, you must inject them.

The Duplication of HTTP Requests.

Think about the scenario when your app requests data from the back end and then shows it to the user.

The server sends an HTTP request for the requested data when the page requests it. Before rendering the page, it waits for the HTTP Request to be completed. The page is then delivered to the browser by the server. The page and the data are immediately displayed by the browser.

The Angular framework is now downloaded and bootstrapped by Browser. Duplication occurs because Angular makes the same HTTP request twice to obtain the data.

Use of the BrowserTransferStateModule and ServerTransferStateModule can help to mitigate that.

Make URL Absolute

Make sure to use absolute URLs when sending HTTP queries from the client-side. During the SSR, the requests with relative URLs fail.

HTTP Security

The server rejects the authenticated HTTP Request for data to the backend server. because the client's saved authentication cookies are inaccessible to the server. The security on the server side will be your responsibility.

Browser Events

The browser instantly displays the rendered HTML that SSR Apps gives to it. The Angular Framework is downloaded by the browser in the background, and it is then bootstrapped.

Because Angular hasn't loaded, the user sees a non-interactive page in between these two occurrences. Events like button clicks and mouse movements are not recorded.

PreBoot Library can be used to get around this issue. Once the app is interactive, it replays every event. As a result, the user need not repeat the actions.

Conclusion

How to construct Server Side Rendering was covered in this Angular Universal Tutorial. When you want your app to be search engine friendly, the SSR is helpful.

I hope this article helps you and you will like it.👍

If you have any doubt or confusion then free to ask in the comment section.

Post a Comment

Previous Post Next Post