Skip to main content

Angular Firebase Deployment

Introduction

Firebase Hosting is a popular choice for deploying Angular applications due to its simplicity, speed, and integration with other Firebase services. In this tutorial, you'll learn how to deploy your Angular application to Firebase Hosting from scratch, including setting up Firebase, configuring your project, and implementing continuous deployment workflows.

Firebase Hosting offers several benefits for Angular applications:

  • Global CDN (Content Delivery Network) for fast content delivery
  • Automatic SSL certificates for secure connections
  • Easy rollbacks to previous versions
  • Simple CLI deployment process
  • Integration with other Firebase services (Authentication, Database, etc.)

Prerequisites

Before you begin, make sure you have:

  • An Angular project ready for deployment
  • Node.js and npm installed
  • A Google account for Firebase access
  • Angular CLI installed (npm install -g @angular/cli)

Setting Up Firebase

Step 1: Install Firebase CLI

First, you need to install the Firebase Command Line Interface (CLI) which will allow you to interact with Firebase from your terminal:

bash
npm install -g firebase-tools

Step 2: Login to Firebase

After installation, authenticate with your Google account:

bash
firebase login

This command will open a browser window where you'll sign in with your Google account and authorize the Firebase CLI.

Preparing Your Angular Project

Step 3: Build Your Angular Application

Before deploying, you need to create a production build of your Angular application:

bash
ng build

This command compiles your application into the dist/<project-name> directory by default. The built files are optimized for production with minified code and efficient bundling.

Configuring Firebase for Your Project

Step 4: Initialize Firebase in Your Project

Navigate to your project's root directory and initialize Firebase:

bash
firebase init

You'll be prompted to:

  1. Select Firebase features - choose "Hosting"
  2. Select a Firebase project or create a new one
  3. Specify your public directory (usually dist/<project-name>)
  4. Configure as a single-page application
  5. Set up automatic builds and deploys (optional)

Your selections will create a firebase.json configuration file that looks something like this:

json
{
"hosting": {
"public": "dist/your-app-name",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
]
}
}

The rewrites section is particularly important for Angular applications as it ensures that all routes are directed to index.html, allowing Angular's router to handle client-side navigation.

Deploying Your Angular Application

Step 5: Deploy to Firebase

Now you can deploy your application with a single command:

bash
firebase deploy

After a successful deployment, you'll see output similar to:

✔ Deploy complete!

Project Console: https://console.firebase.google.com/project/your-project-id/overview
Hosting URL: https://your-project-id.web.app

Your application is now live at the provided Hosting URL!

Advanced Configuration Options

Custom Domain Setup

If you want to use your own domain instead of the default Firebase domain:

  1. Go to the Firebase Console
  2. Select your project
  3. Navigate to Hosting
  4. Click on "Add custom domain"
  5. Follow the verification and DNS configuration steps

Environment-Specific Deployments

For projects with multiple environments (development, staging, production), you can create multiple Firebase projects and use targets:

bash
firebase use --add

Then configure targets in your firebase.json:

json
{
"hosting": {
"target": "production",
"public": "dist/your-app-name"
}
}

Deploy to a specific target:

bash
firebase deploy --only hosting:production

Setting Up Continuous Deployment

GitHub Actions Integration

Create a .github/workflows/firebase-deploy.yml file:

yaml
name: Deploy to Firebase Hosting
on:
push:
branches:
- main
jobs:
build_and_deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: '16'
- run: npm ci
- run: npm run build
- uses: FirebaseExtended/action-hosting-deploy@v0
with:
repoToken: '${{ secrets.GITHUB_TOKEN }}'
firebaseServiceAccount: '${{ secrets.FIREBASE_SERVICE_ACCOUNT }}'
channelId: live
projectId: your-firebase-project-id

For this to work, you'll need to add a Firebase service account secret to your GitHub repository.

Real-world Example: Deploying an Angular Blog

Let's walk through a complete example of deploying a simple Angular blog application to Firebase.

  1. Create an Angular application:
bash
ng new angular-blog --routing
cd angular-blog
ng generate component blog-list
ng generate component blog-post
  1. Add some basic blog functionality (simplified):
typescript
// src/app/blog.service.ts
import { Injectable } from '@angular/core';

export interface BlogPost {
id: number;
title: string;
content: string;
}

@Injectable({
providedIn: 'root'
})
export class BlogService {
private posts: BlogPost[] = [
{ id: 1, title: 'Getting Started with Angular', content: 'This is your first post!' },
{ id: 2, title: 'Deploying to Firebase', content: 'Learn how to deploy Angular apps.' }
];

getPosts(): BlogPost[] {
return this.posts;
}

getPost(id: number): BlogPost | undefined {
return this.posts.find(post => post.id === id);
}
}
  1. Update the components and routing:
typescript
// src/app/app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { BlogListComponent } from './blog-list/blog-list.component';
import { BlogPostComponent } from './blog-post/blog-post.component';

const routes: Routes = [
{ path: '', component: BlogListComponent },
{ path: 'post/:id', component: BlogPostComponent }
];

@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
  1. Build the application:
bash
ng build
  1. Initialize and deploy to Firebase:
bash
firebase init
# Follow the prompts as described earlier
firebase deploy

Your blog application is now deployed to Firebase Hosting!

Optimization Tips

Enable Caching

Update your firebase.json to include caching headers:

json
{
"hosting": {
"public": "dist/your-app-name",
"ignore": ["firebase.json", "**/.*", "**/node_modules/**"],
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
],
"headers": [
{
"source": "**/*.@(jpg|jpeg|gif|png|svg|webp)",
"headers": [
{
"key": "Cache-Control",
"value": "max-age=86400"
}
]
},
{
"source": "**/*.@(js|css)",
"headers": [
{
"key": "Cache-Control",
"value": "max-age=31536000"
}
]
}
]
}
}

Pre-rendering for SEO

For better SEO, consider adding Angular Universal for server-side rendering or pre-rendering:

bash
ng add @nguniversal/express-engine

Troubleshooting Common Issues

Issue: "Error: No default project"

Solution: Specify your project ID:

bash
firebase use your-project-id

Issue: Routing doesn't work after deployment

Solution: Ensure you have the proper rewrite rules in firebase.json and have configured your Angular app as a single-page application during Firebase initialization.

Summary

In this tutorial, you've learned how to deploy an Angular application to Firebase Hosting, including:

  • Setting up the Firebase CLI and environment
  • Configuring your Angular project for Firebase deployment
  • Deploying your application
  • Implementing advanced features like custom domains and continuous deployment
  • Optimizing your deployment for performance and SEO

Firebase Hosting provides a robust, simple, and efficient way to deploy your Angular applications, with features that integrate well with Angular's architecture and requirements.

Additional Resources

Exercises

  1. Deploy an existing Angular application to Firebase Hosting.
  2. Set up continuous deployment using GitHub Actions.
  3. Configure a custom domain for your Firebase-hosted application.
  4. Implement different Firebase environments for development and production.
  5. Add Firebase Analytics to track user engagement on your deployed application.


If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)