Angular Performance Boost: Unlocking SSR with Cloud Functions

In this guide, we will demonstrate the steps to prepare your Angular project for Server-Side Rendering using Angular Universal. Additionally, I’ll explain the process of deploying it to Firebase by utilizing Firebase Hosting and Cloud Functions.

How does an Angular Application Differ from a Server-Side Rendered Angular Application?

When you deploy a standard Angular application online, it’s downloaded and executed within the browser. In this setup, each page is created locally within the browser, responding to user interactions. However, when you employ Server-Side Rendering with Angular Universal, parts of each page are pre-rendered on the server, while the remainder is handled in the browser.

This approach enhances rendering speed and enables better visibility on search engines and social media platforms through meta elements.

Angular Application Without Server-Side Rendering

Due to the functioning of a typical Angular application, you’ll consistently encounter identical meta information across all pages. Initially, the main HTML page of your application is fetched from the server, after which the application generates content locally on the user’s device.

As a result, search engines and social media platforms may perceive your site as having only one page due to its reliance on meta elements.

Angular Application with Server-Side Rendering

Through Server-Side Rendering, distinct HTML pages are generated for each page within the application as they are crafted on the server. This allows for the incorporation of diverse meta-elements on each page.

Page 1:

<!doctype html>
<html lang="en">
<head>
<title>Page 1</title>
<meta name="description" content="...">
</head>
<body>
</html>

Page 2:

<!doctype html>
<html lang="en">
<head>
<title>Page 2</title>
<meta name="description" content="...">
</head>
<body>
</html>

Adapting Your Application for Server-Side Rendering

To get started, launch a new or existing Angular project in your preferred code editor and integrate Angular Universal into the project.

Run 
ng add @nguniversal/express-engine.

This command will generate and modify several files within the project, completing the necessary setup. With this, your application is now primed for Server-Side Rendering.

Deploying the Application to Firebase

To deploy the project to Firebase, navigate to the angular.json file and modify the output path for the build. Replace the project’s name with “functions”, then scroll down to locate the server property and perform the same modification.

"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/functions/browser",
"index": "src/index.html",
"main": "src/main.ts",
"..."
},
...
"server": {
"builder": "@angular-devkit/build-angular:server",
"options": {
"outputPath": "dist/functions/server",
"main": "server.ts",
"tsConfig": "tsconfig.server.json"
},

By making this adjustment, the production files will be placed within a folder named “functions” upon project build. Save the project, and in the terminal, execute npm run build:ssr to compile the project.

npm run build:ssr

Once the project is compiled, you’ll notice a directory named “dist.” Within this directory lies another folder titled “functions,” containing the production files.

Now locate the file called server.ts. This file becomes part of the project once you execute the command for adding Angular Universal. The code in this file is what the server will look at when generating the web pages.

import 'zone.js/dist/zone-node';

import { ngExpressEngine } from '@nguniversal/express-engine';
import * as express from 'express';
import { join } from 'path';

import { AppServerModule } from './src/main.server';
import { APP_BASE_HREF } from '@angular/common';
import { existsSync } from 'fs';

export function app(): express.Express {
const server = express();
const distFolder = join(process.cwd(), "dist/angular-ssr-demo/browser");
const indexHtml = existsSync(join(distFolder, 'index.original.html')) ? 'index.original.html' : 'index';


server.engine('html', ngExpressEngine({
bootstrap: AppServerModule,
}));

server.set('view engine', 'html');
server.set('views', distFolder);

server.get('*.*', express.static(distFolder, {
maxAge: '1y'
}));

server.get('*', (request, response) => {
response.render(indexHtml, { request, providers: [{ provide: APP_BASE_HREF, useValue: request.baseUrl }] });
});

return server;
}

In the distFolder setting, substitute the project name with “functions” as well. This modification is essential as it instructs the server where to locate the files for our pages, which reside within the “browser” folder.

const distFolder = join(process.cwd(), "dist/functions/browser");

Yet, this path is functional solely for local testing on the computer. In a testing environment, the root directory corresponds to the location of the server.ts file, while our website files are located in the dist/functions/browser directory.

When deploying the project to Cloud Functions, the root directory shifts to the functions directory. Consequently, the previously defined path will no longer lead to the website files.

To address this issue, establish a variable and utilize the production property within the environment object to ascertain whether the environment is set to test or production mode.

In the event of a production environment, return “browser” since the web files reside within the browser folder. If not, return “dist/functions/browser”.

const webLocation = environment.production? "browser" : "dist/functions/browser";

Substitute the string for the distFolder with the variable and ensure to save the project.

const distFolder = join(process.cwd(), webLocation );

Instead of utilizing ng serve to initiate the local server, employ npm run dev:ssr in the terminal. Once the server is operational, open your application in the browser. If your application functions properly, it indicates readiness for testing the code in production mode. Terminate the server session in the terminal and navigate into the dist directory.

cd dist

Proceed by initializing Firebase hosting.

Related read: What is Firebase: The Good and the Bad of Firebase Backend Services

Transform Your Angular App with SSR and Cloud Functions!

Setting Up Firebase Hosting

firebase init

Specify the location of the browser folder for the public directory and configure it as a single-page application.

Configuring Firebase Cloud Functions

Once Hosting setup is complete, proceed with initializing Cloud Functions. Ensure that the necessary dependencies

firebase init

After the Cloud Functions setup is finalized, navigate to the package.json file for the project and copy all the dependencies. Subsequently, access the package.json file for Cloud Functions and include these dependencies in its dependencies section.

Save the project, then navigate to the Functions directory in the terminal and proceed to install the packages.

npm install

Upon completion of package installation, access the index.js file and establish a request function for Cloud Functions.

exports.angularssrapp = functions.https.onRequest();

Within the parenthesis of the request, utilize the express app function sourced from the server.ts file.

Server.ts

export function app(): express.Express {
const server = express();
...
return server;
}

Once the project is compiled, this code will be generated in the main.js file within the server folder. To access the app function, return to the index.js file, import the main.js file, and subsequently pass the app() function within the request.

const functions = require("firebase-functions");

const mainJs = require(__dirname + "/server/main");
exports.angularssrapp = functions.https.onRequest(mainJs .app());

Final Step: Adjusting the Firebase.json Configuration File

The final adjustment entails accessing the firebase.json file and updating the destination to “function” within the rewrites array. This instructs Firebase Hosting to invoke a function from Cloud Functions instead of utilizing an HTML page.

For the content, substitute it with the designated function name you intend to call. Ensure that it corresponds precisely to the name specified in the index.js file; otherwise, it will not function correctly.

{
"hosting": {
"public": "functions/browser",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites": [
{
"source": "**",
"function": "angularssrdemo"
}
]
}
}

Save your project and execute Firebase emulators: start in the terminal.

firebase emulators:start

Executing this command enables testing of our code within a Firebase environment before deployment. Copy the generated hosting address and paste it into your browser for testing.

localhost:5000

If your application is functioning properly, it’s prepared for deployment to Firebase. Navigate to the terminal for the dist directory and proceed to deploy functions and hosting to Firebase.

firebase deploy -- only hosting,functions
coma

Conclusion

In conclusion, implementing Server-Side Rendering (SSR) with Angular Universal and deploying the application to Firebase using Cloud Functions can significantly enhance the performance and visibility of your Angular project.

By pre-rendering parts of each page on the server and incorporating diverse meta-elements, SSR improves rendering speed and ensures better search engine and social media visibility. Follow the step-by-step guide provided to adapt your Angular application for SSR and deploy it seamlessly to Firebase, optimizing its performance and accessibility.

Keep Reading

Keep Reading

  • Service
  • Career
  • Let's create something together!

  • We’re looking for the best. Are you in?