Angular Universal on Cloud Functions or AppEngine

Fireship · Beginner ·🌐 Frontend Engineering ·7y ago

Key Takeaways

The video demonstrates how to set up Angular Universal for server-side rendering and deploy it to Firebase Cloud Functions or Google App Engine, using tools like Angular Fire, Express.js, and Firebase.

Full Transcript

[Music] one of the biggest challenges with building a single page application is making the app visible to search engines and Link BOTS fortunately with angular Universal we have a reliable package for rendering our apps on the server not only does this provide SEO but it can also improve the initial page load speed in today's video you'll learn how to server-side render an angular app then deploy it to Google App Engine or firebase cloud functions if you're new here like and subscribe and make sure to follow along with the full source code on fire ship io let's start by talking about what server-side rendering is and when you would want to use it in any normal JavaScript app whether it be angular view or react you will provide the browser with a JavaScript bundle then the browser will parse that bundle of JavaScript and figure out how to render the HTML that's a great way to build a modern web app because it will make the user experience feel very fast and responsive like a native app but the problem is that a lot of bots out there don't execute JavaScript so that means if somebody shares a deep link in your app and that link renders some kind of dynamic content the only thing the bot will see is your initial index.html file so the purpose of angular Universal and server-side rendering is to offload some of this work to the server so when the user first visits a deep link they'll get some rendered HTML with the dynamic content already included for example the Twitter bot just wants to read the meta tags and ahead of the document so it's just going to grab that HTML and then not worry about executing any JavaScript on the page when you have just a regular user they'll get that same pre-rendered HTML so this usually results in a faster initial page load then angular's JavaScript will take over so it'll behave just like a regular angular app on subsequent navigations in order to make this possible we can't really use firebase hosting directly because it's just a static host we need an actual node.js server to dynamically render the content when a page is requested we have two good deployment options for a firebase project Google App Engine and firebase cloud functions there are some trade-offs between the two but I'll show you how to set up both of them in this video and they can both be used on the free tier I'm starting out from a brand new angular 7 app and the great thing about Universal is that there's a schematic so we can simply add all the boilerplate to our project by running this command ng ad universal express engine and then specify the client project as your project that will create five new files in this project so let's take a look at each one of those now the first one is the web pack server config and its job is to package and compile the server dot es file so let's jump into server TS and you'll see that this is our actual Express j/s app Express is a tool that can receive a web request and then send a response back to the browser so Express will save the initial request angular Universal will kick in and render the actual HTML and Express we'll send that HTML as a response to the browser you'll also see a main server dot ES file which is just the entry point into the server-side app and it also has its own TS config from there we'll jump into the app directory and you'll see we also have an app server module it's basically just a wrapper around the app module and at this point you don't have to make any changes to any of these files once we get to the firebase stuff I'll show you exactly what needs to change and where so let's go ahead and install angular fire and firebase and then we'll jump into the app module you'll notice one change here and that's that the browser module is now calling with server transition that just allows the app to be rendered on the server and then transition into a normal angular app after the initial page load from there you can import all of the angular fire stuff that you want to use in your project none of this stuff is actually required for angular universal but I'm just making the assumption that you have firebase in your project because there's a few caveats that we'll look at later that takes care of the initial setup now let's go into the package.json and you'll see that the ng add command added a few new npm scripts to this file the ones that you want to use primarily are build SSR and serve SSR first we'll build the app and then we'll go ahead and serve it just to make sure everything is working at this point now just a quick side note I highly recommend using node version 8.1 for when working in your local development environment that's the version used on GCP and cloud functions and that's what I use to build this tutorial after running the build command you should see a disk directory and inside of that you should see a browser build and a server build as well as a server JS file at this point our app doesn't really do anything so I'm going to go ahead and generate a new component that represents the about page for this app then we'll have this page dynamically render its own meta tags so can be used with a Twitter card or any other social media site if you run ng generate components you'll probably get an error saying it's missing the module you can fix that by adding flag with app to your command that happens because there's two modules in the app directory and it doesn't know which one to use when it comes to SEO you'll most likely want to set a title and some meta tags when this component is rendered and angular provides a couple of services for you to do that called title and meta then I'm going to create an object with just some static data but you could also pull this data from the database from there we'll go ahead and inject our dependencies in the constructor and then with title we can just simply call set title and then pass the dynamic data to it then the meta service has an add tags method which we can pass an array of multiple meta tags you can learn how to format meta tags by going to the Open Graph Docs or to Twitter or Facebook but basically angular is just going to add these tags to the head of the document when this component is initialized the one thing that is very important is that you use this service to set the meta tags and not do it manually on the document or window itself for example if we wanted to get the URL it's tempting to call window location path name but the window doesn't exist in node J s so this will result in an error when we try to server-side render the app so when using Universal you always want to keep that in mind and just try to avoid touching the Dom directly so in order for this to be useful to us we need to have this component loaded by the router if we jump over to the app routing module we can just set up a single path to about that loads the about component at this point you should be able to load the app in the browser just using ng serve and you should see the meta tags in the head of the document so at this point we have dynamic meta tags but if we were to share this link on social media we'd end up with something like this and again that's because the meta tags are rendered by the JavaScript now let's go ahead and serve this app with Universal so the meta tags are rendered in advance first run the build SSR command after that's done run serve SSR that will serve the app on localhost 4000 but if you're using firebase in your project you should end up with an error like this that's because firebase uses a few things in the Dom that are not available on node by default but we can easily fix that by just adding in polyfills for them first install WebSockets and xhr to into your development environment from there go into the server TS file and then add these two lines to the very top of it if you're in the serve command again it should work but it'll still give you a couple of warnings you can clear out these warnings by installing these packages and that command is available in the full and anytime you make changes to this file make sure to run the build SSR command first and then serve SSR after at this point you can go to localhost 4000 and your app should look and behave just like a normal angular app but you can validate that your server-side rendering is working by opening up the page source this is how the page looks when it's served to the browser so before any JavaScript is run and you know it's working if you see your meta tags and your dynamic title in this HTML now we have a big decision to make do we deploy this to Google App Engine or to firebase cloud functions on App Engine our project will become a containerized app so it can be deployed on App Engine or any other cloud and there's a free tier for nodejs and it will scale up automatically as needed and the pricing works out to be around twenty-five dollars per month per container but they will Auto scale based on the traffic and demand so that pricing will vary App Engine is also very easy to deploy to so in my opinion it's the better way to go in most cases but it's also possible to deploy to cloud functions which gives you a tighter integration with firebase and it's hard to do a direct price comparison but I suspect cloud functions would be less expensive pricing is based on the number of invocations of the function which is free up to 125-thousand per month so those are the trade-offs let's go ahead and deploy to App Engine first you need to have the Google Cloud command-line tools installed so you should be able to run the g-cloud command and then we'll create a file called App Gamal the only line you need in this file is the runtime as nodejs 8 but you can also specify a different scaling options here as well when you deploy it's going to be looking for the NPM run start command so you'll want to go into your package JSON and have that point to the service SR command from there it's just a matter of running g-cloud app deploy and that will push the container to Google Cloud and start running it as a service that should take a couple minutes but when it's done it will give you a URL and when you go there it should have the same exact app that we were looking at on localhost and the nice thing about App Engine is that we have this dashboard where we can look at the different versions we can look at the debug logs and we can even look at the source code so that was super easy now let's take a look at cloud functions which requires a few more steps the first thing we want to do is run firebase submit for hosting and functions I'm going to use typescript functions but the process is almost identical for JavaScript functions from there go ahead and point to the dist browser directory and you'll say yes to configuring the app as a single page app we'll go ahead and configure it to rewrite all of the traffic to a cloud function instead of the index.html like it normally does you can name this whatever you want but I'll just go ahead and call it SSR now we need to see the into the functions directory and we need a way to get our angular code into our functions environment because Universal needs that source code in the runtime to render the actual content I'm going to write a little note script here to handle that and to make life a little bit easier I'm installing file system extra then we'll create a file called CP - angularjs now there are many different ways we can do this but this is the way I chose to do it basically we just have a function that will copy the files from the dist directory and angular over to a dist folder in the functions directory then we'll also always want to remove the copied files on each new build of cloud functions just to make sure we're always working with the latest angular code from there go into the package.json for functions and read node CP angular in your build command and while we're in here let's also set the engine to note 8 so that it deploys our function as a note 8 function now we'll go to the source index TS and write the function itself it's actually super easy all we have to do is take the universal app and then pass it into an HTTP function as you can see here we're actually importing the universal app from our current working directory so that's why we have to copy it over to the functions environment and that's all there is to the function side of things but in order for this to work we need to make a couple of tweaks to the original server code and angular open up the server TS file and then add an export in front of the app variable then go all the way down at the bottom and comment out the listener cloud functions is already doing it listening so we don't want this line in our code and we need to make sure that our code gets exported as a library that we can consume so add library app and library target UMD and if you have issues bundling you may want to add firebase as an external now it's time for the moment of truth first make sure to rebuild your app using the build SS our command and angular then go into the functions directory and run the build command there from there run firebase serve which will serve your hosting and your function simultaneously hopefully everything went well and you're seeing the rendered meta tags when you go to localhost 5,000 if that's the case go ahead and run firebase deploy and that will deploy the function and hosting and now you have a fully server-side rendered app running on firebase cloud functions after deploys head over to the Twitter card validator just to make sure that everything is working as expected I'm gonna go ahead and wrap things up there if you run into any issues let me know in the comments or on slat thanks for watching and I will talk to you soon [Music]

Original Description

Learn how to perform serverside rendering (SSR) with Angular Universal, then deploy to Firebase Cloud Functions or GCP AppEngine https://fireship.io/lessons/angular-universal-firebase/ for better perf and SEO Universal - https://angular.io/guide/universal Functions - https://firebase.google.com/docs/functions GCP https://cloud.google.com/sdk
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Fireship · Fireship · 0 of 60

← Previous Next →
1 Angular 4 Development and Production Environments with Firebase
Angular 4 Development and Production Environments with Firebase
Fireship
2 OAuth with Angular and Firebase Tutorial
OAuth with Angular and Firebase Tutorial
Fireship
3 Anonymous Authentication with Angular and Firebase - Lazy Registration
Anonymous Authentication with Angular and Firebase - Lazy Registration
Fireship
4 Angular Router Guards for Firebase Users
Angular Router Guards for Firebase Users
Fireship
5 Angular Firebase CRUD App with NoSQL Database Tutorial
Angular Firebase CRUD App with NoSQL Database Tutorial
Fireship
6 Upload Files from Angular to Firebase Storage
Upload Files from Angular to Firebase Storage
Fireship
7 How to Deploy an Angular App to Firebase Hosting
How to Deploy an Angular App to Firebase Hosting
Fireship
8 Sharing Data between Components in Angular
Sharing Data between Components in Angular
Fireship
9 Loading Spinners for Asynchronous Firebase Data
Loading Spinners for Asynchronous Firebase Data
Fireship
10 Angular 4 Transactional Email with Google Firebase Cloud Functions
Angular 4 Transactional Email with Google Firebase Cloud Functions
Fireship
11 Firebase Database Rules Tutorial
Firebase Database Rules Tutorial
Fireship
12 Autocomplete Search with Angular4 and Firebase
Autocomplete Search with Angular4 and Firebase
Fireship
13 Reddit Inspired Upvoting System with Angular and Firebase NoSQL
Reddit Inspired Upvoting System with Angular and Firebase NoSQL
Fireship
14 Angular Drag-and-Drop File Uploads to Firebase Storage
Angular Drag-and-Drop File Uploads to Firebase Storage
Fireship
15 Text Translation with Firebase Cloud Functions onWrite and Angular 4
Text Translation with Firebase Cloud Functions onWrite and Angular 4
Fireship
16 Custom Usernames with Firebase Authentication
Custom Usernames with Firebase Authentication
Fireship
17 Twitter-Inspired Follow Unfollow Feature with Firebase and Angular 4
Twitter-Inspired Follow Unfollow Feature with Firebase and Angular 4
Fireship
18 Simple Pagination with Firebase and Angular 4
Simple Pagination with Firebase and Angular 4
Fireship
19 How to Connect Firebase Users to their Data - 3 Methods
How to Connect Firebase Users to their Data - 3 Methods
Fireship
20 Add Toast Message Notifications to your Angular App
Add Toast Message Notifications to your Angular App
Fireship
21 Facebook-Inspired Reactions System with Angular and Firebase
Facebook-Inspired Reactions System with Angular and Firebase
Fireship
22 Learn NgModule in Angular with Examples
Learn NgModule in Angular with Examples
Fireship
23 Lazy Loading Components in Angular 4
Lazy Loading Components in Angular 4
Fireship
24 Stripe Checkout Payments with Angular and Firebase - Part 1
Stripe Checkout Payments with Angular and Firebase - Part 1
Fireship
25 Process Stripe Payments with Firebase Cloud Functions - Part 2
Process Stripe Payments with Firebase Cloud Functions - Part 2
Fireship
26 Selling Digital Content in Angular with Stripe Payments - Part 3
Selling Digital Content in Angular with Stripe Payments - Part 3
Fireship
27 Angular 4 Full Text Search with Algolia - Part 1
Angular 4 Full Text Search with Algolia - Part 1
Fireship
28 Algolia with Firebase Cloud Functions - Part 2
Algolia with Firebase Cloud Functions - Part 2
Fireship
29 Firebase Phone Authentication in Angular 4
Firebase Phone Authentication in Angular 4
Fireship
30 Top 7 RxJS Concepts for Angular Developers
Top 7 RxJS Concepts for Angular Developers
Fireship
31 Learn Angular Animations with 5 Examples
Learn Angular Animations with 5 Examples
Fireship
32 Advanced Firebase Data Filtering (Multi-Property)
Advanced Firebase Data Filtering (Multi-Property)
Fireship
33 Realtime Maps with Mapbox + Firebase + Angular
Realtime Maps with Mapbox + Firebase + Angular
Fireship
34 Angular Reactive Forms with Firebase Database Backend
Angular Reactive Forms with Firebase Database Backend
Fireship
35 Send Push Notifications in Angular with Firebase Cloud Messaging
Send Push Notifications in Angular with Firebase Cloud Messaging
Fireship
36 Top 7 Ways to Debug Angular 4 Apps
Top 7 Ways to Debug Angular 4 Apps
Fireship
37 Infinite Scroll with Angular and Firebase
Infinite Scroll with Angular and Firebase
Fireship
38 Use TypeScript with Firebase Cloud Functions
Use TypeScript with Firebase Cloud Functions
Fireship
39 Realtime Graphs and Charts with Plotly and Firebase
Realtime Graphs and Charts with Plotly and Firebase
Fireship
40 Role-Based User Permissions in Firebase
Role-Based User Permissions in Firebase
Fireship
41 User Presence System in Realtime - Online, Offline, Away
User Presence System in Realtime - Online, Offline, Away
Fireship
42 Location-based Queries with GeoFire and Angular Google Maps
Location-based Queries with GeoFire and Angular Google Maps
Fireship
43 Angular ngrx Redux Quick Start Tutorial
Angular ngrx Redux Quick Start Tutorial
Fireship
44 Angular Ngrx Effects with Firebase Database
Angular Ngrx Effects with Firebase Database
Fireship
45 Progressive Web Apps with Angular
Progressive Web Apps with Angular
Fireship
46 Angular Ngrx with Firebase Google OAuth User Authentication
Angular Ngrx with Firebase Google OAuth User Authentication
Fireship
47 RxJS Quick Start with Practical Examples
RxJS Quick Start with Practical Examples
Fireship
48 Send SMS Text Messages with Twilio and Firebase
Send SMS Text Messages with Twilio and Firebase
Fireship
49 Firebase Database Performance Profiling
Firebase Database Performance Profiling
Fireship
50 Native Desktop Apps with Angular and Electron
Native Desktop Apps with Angular and Electron
Fireship
51 Subscription Payments with Stripe, Angular, and Firebase
Subscription Payments with Stripe, Angular, and Firebase
Fireship
52 Firestore with AngularFire5 Quick Start Tutorial
Firestore with AngularFire5 Quick Start Tutorial
Fireship
53 Angular HTTP Client Quick Start Tutorial
Angular HTTP Client Quick Start Tutorial
Fireship
54 Google Sign-In with Firestore Custom User Data
Google Sign-In with Firestore Custom User Data
Fireship
55 Star Review System from Scratch with Firestore + Angular
Star Review System from Scratch with Firestore + Angular
Fireship
56 Angular Chatbot with Dialogflow (API.ai)
Angular Chatbot with Dialogflow (API.ai)
Fireship
57 Learn @ngrx/entity and Feature Modules
Learn @ngrx/entity and Feature Modules
Fireship
58 Infinite Scroll Pagination with Firestore
Infinite Scroll Pagination with Firestore
Fireship
59 Faster Firestore via Data Aggregation
Faster Firestore via Data Aggregation
Fireship
60 Contentful - CMS for Angular Progressive Web Apps
Contentful - CMS for Angular Progressive Web Apps
Fireship

This video teaches how to set up Angular Universal for server-side rendering and deploy it to Firebase Cloud Functions or Google App Engine, improving initial page load speed and SEO. It covers the setup of Angular Universal, configuration of server-side rendering, and deployment to cloud functions or app engine.

Key Takeaways
  1. Run ng add universal express engine to add boilerplate to the project
  2. Install Angular Fire and Firebase
  3. Configure Angular Universal with server-side rendering
  4. Generate a new component for the about page with dynamic meta tags
  5. Use the title and meta services to set meta tags
  6. Serve the app with Universal to render meta tags in advance
  7. Deploy to Google App Engine or Firebase Cloud Functions
💡 Server-side rendering with Angular Universal can improve initial page load speed and provide better SEO by pre-rendering HTML with dynamic content for bots and users.

Related AI Lessons

Up next
The masks we wear | Zora Krstić | TEDxLuxembourgCity
TEDx Talks
Watch →