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.
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.
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.
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>
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.
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
firebase init
Specify the location of the browser folder for the public directory and configure it as a single-page application.
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.
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());
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
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.
How to Effectively Hire and Manage a Remote Team of Developers.
Download NowMindbowser played a crucial role in helping us bring everything together into a unified, cohesive product. Their commitment to industry-standard coding practices made an enormous difference, allowing developers to seamlessly transition in and out of the project without any confusion....
CEO, MarketsAI
I'm thrilled to be partnering with Mindbowser on our journey with TravelRite. The collaboration has been exceptional, and I’m truly grateful for the dedication and expertise the team has brought to the development process. Their commitment to our mission is...
Founder & CEO, TravelRite
The Mindbowser team's professionalism consistently impressed me. Their commitment to quality shone through in every aspect of the project. They truly went the extra mile, ensuring they understood our needs perfectly and were always willing to invest the time to...
CTO, New Day Therapeutics
I collaborated with Mindbowser for several years on a complex SaaS platform project. They took over a partially completed project and successfully transformed it into a fully functional and robust platform. Throughout the entire process, the quality of their work...
President, E.B. Carlson
Mindbowser and team are professional, talented and very responsive. They got us through a challenging situation with our IOT product successfully. They will be our go to dev team going forward.
Founder, Cascada
Amazing team to work with. Very responsive and very skilled in both front and backend engineering. Looking forward to our next project together.
Co-Founder, Emerge
The team is great to work with. Very professional, on task, and efficient.
Founder, PeriopMD
I can not express enough how pleased we are with the whole team. From the first call and meeting, they took our vision and ran with it. Communication was easy and everyone was flexible to our schedule. I’m excited to...
Founder, Seeke
Mindbowser has truly been foundational in my journey from concept to design and onto that final launch phase.
CEO, KickSnap
We had very close go live timeline and Mindbowser team got us live a month before.
CEO, BuyNow WorldWide
If you want a team of great developers, I recommend them for the next project.
Founder, Teach Reach
Mindbowser built both iOS and Android apps for Mindworks, that have stood the test of time. 5 years later they still function quite beautifully. Their team always met their objectives and I'm very happy with the end result. Thank you!
Founder, Mindworks
Mindbowser has delivered a much better quality product than our previous tech vendors. Our product is stable and passed Well Architected Framework Review from AWS.
CEO, PurpleAnt
I am happy to share that we got USD 10k in cloud credits courtesy of our friends at Mindbowser. Thank you Pravin and Ayush, this means a lot to us.
CTO, Shortlist
Mindbowser is one of the reasons that our app is successful. These guys have been a great team.
Founder & CEO, MangoMirror
Kudos for all your hard work and diligence on the Telehealth platform project. You made it possible.
CEO, ThriveHealth
Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.
CEO, SMILINGMIND
They were a very responsive team! Extremely easy to communicate and work with!
Founder & CEO, TotTech
We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.
Co-Founder, TEAM8s
Mindbowser was very helpful with explaining the development process and started quickly on the project.
Executive Director of Product Development, Innovation Lab
The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs.
Co-Founder, Vesica
Mindbowser is professional, efficient and thorough.
Consultant, XPRIZE
Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.
Founder, S.T.A.R.S of Wellness
Mindbowser was great; they listened to us a lot and helped us hone in on the actual idea of the app. They had put together fantastic wireframes for us.
Co-Founder, Flat Earth
Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.
Founder, Child Life On Call
The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!
CEO, SDOH2Health LLC
Mindbowser was easy to work with and hit the ground running, immediately feeling like part of our team.
CEO, Stealth Startup
Mindbowser was an excellent partner in developing my fitness app. They were patient, attentive, & understood my business needs. The end product exceeded my expectations. Thrilled to share it globally.
Owner, Phalanx
Mindbowser's expertise in tech, process & mobile development made them our choice for our app. The team was dedicated to the process & delivered high-quality features on time. They also gave valuable industry advice. Highly recommend them for app development...
Co-Founder, Fox&Fork