How to Host Angular App on Firebase
How to Host Angular App on Firebase Hosting an Angular application on Firebase is one of the most efficient, scalable, and cost-effective ways to deploy modern web applications. Firebase, Google’s backend-as-a-service platform, offers a seamless, high-performance hosting solution optimized for static sites—perfect for Angular apps built with Ahead-of-Time (AOT) compilation and lazy loading. With b
How to Host Angular App on Firebase
Hosting an Angular application on Firebase is one of the most efficient, scalable, and cost-effective ways to deploy modern web applications. Firebase, Googles backend-as-a-service platform, offers a seamless, high-performance hosting solution optimized for static sitesperfect for Angular apps built with Ahead-of-Time (AOT) compilation and lazy loading. With built-in SSL, global CDN distribution, and automatic cache invalidation, Firebase Hosting eliminates the complexity of traditional server management while delivering lightning-fast load times to users worldwide.
This tutorial provides a comprehensive, step-by-step guide to deploying your Angular application on Firebase Hostingfrom setting up your project to optimizing performance and troubleshooting common issues. Whether youre a beginner taking your first steps in web deployment or an experienced developer seeking to refine your workflow, this guide ensures you understand every aspect of the process. By the end, youll not only know how to host your Angular app on Firebase but also how to do it securely, efficiently, and at scale.
Step-by-Step Guide
Prerequisites
Before you begin, ensure you have the following installed and configured:
- Node.js and npm: Angular requires Node.js (v16 or higher) and npm (v8 or higher). Verify your installation by running
node -vandnpm -vin your terminal. - Angular CLI: Install the Angular CLI globally using
npm install -g @angular/cli. Confirm installation withng version. - Firebase CLI: Install Firebase tools globally via
npm install -g firebase-tools. Log in to your Firebase account usingfirebase loginin your terminal. - A Firebase Project: If you dont already have one, create a project at Firebase Console. Note your project IDit will be needed later.
Step 1: Create or Prepare Your Angular Project
If youre starting from scratch, generate a new Angular application using the Angular CLI:
ng new my-angular-app
cd my-angular-app
Follow the prompts to configure routing and stylesheet format. Once the project is created, navigate into the directory and serve the app locally to verify it works:
ng serve
Open your browser to http://localhost:4200. You should see the default Angular welcome page.
If youre working with an existing Angular project, ensure it builds successfully by running ng build. The output will be generated in the dist/ folder. The default output path is dist/[project-name], but you can customize it in angular.json under architect.build.options.outputPath.
Step 2: Initialize Firebase in Your Project
From your Angular projects root directory, initialize Firebase:
firebase init
This command launches an interactive setup wizard. Follow these prompts:
- Select Hosting using the spacebar (press Enter to confirm).
- Choose an existing Firebase project or create a new one. If you select an existing project, use the arrow keys to navigate and press Enter.
- When asked, What do you want to use as your public directory?, enter
dist/your-project-name. This is the folder generated byng build. For example, if your project is namedmy-angular-app, typedist/my-angular-app. - For Configure as a single-page app?, select Yes. This ensures Firebase serves
index.htmlfor all routes, which is essential for Angulars client-side routing (e.g.,/about,/contact). - When prompted to overwrite
index.html, select No. Firebase generates a placeholder file, but your Angular build will replace it.
After completion, Firebase creates two critical files in your project root:
firebase.jsonConfiguration file for Firebase Hosting, including rewrite rules and headers..firebasercStores your Firebase project alias for easy switching between environments.
Step 3: Build Your Angular App for Production
Before deploying, you must build your app in production mode. This process minifies code, removes development-only dependencies, and enables optimizations like tree-shaking and AOT compilation.
Run the following command:
ng build --configuration production
Alternatively, if youre using Angular 15+ with the new build system, use:
ng build --prod
This generates optimized files in the dist/your-project-name directory. The output includes:
- Minified JavaScript and CSS files
- Pre-rendered
index.html - Assets like images and fonts
- Service worker (if configured)
Verify the build by opening the index.html file inside the dist/ folder in your browser. Ensure all routes and components load correctly.
Step 4: Deploy to Firebase Hosting
Once your app is built, deploy it to Firebase Hosting with a single command:
firebase deploy
Firebase will upload your files to its global CDN. The output will show:
- Number of files uploaded
- Deployment progress
- Final URL:
https://your-project-id.web.app
Open the provided URL in your browser. Your Angular app is now live on Firebase Hosting.
For faster iteration, you can use the --only hosting flag to deploy only the hosting component:
firebase deploy --only hosting
Step 5: Set Up Custom Domain (Optional)
Firebase Hosting provides a default domain in the format https://[project-id].web.app. For production apps, youll likely want a custom domain like https://myapp.com.
To add a custom domain:
- Go to the Firebase Console ? Hosting ? Connect Domain.
- Enter your domain name (e.g.,
myapp.com) and click Continue. - Firebase will generate DNS records you must add to your domain registrar (e.g., GoDaddy, Cloudflare, Namecheap).
- Typically, youll need to add one or more CNAME records pointing to
your-project-id.web.app. - After DNS propagation (can take minutes to 48 hours), Firebase will automatically provision an SSL certificate via Lets Encrypt.
- Once verified, your custom domain will be active, and traffic will be served over HTTPS.
Important: Always redirect www to non-www (or vice versa) to avoid duplicate content issues. Firebase allows you to configure this in the Hosting settings.
Step 6: Enable Automatic Deployments with GitHub Actions (Optional)
To automate deployments, integrate Firebase with GitHub Actions. This ensures every push to your main branch triggers a build and deploy.
Create a new file at .github/workflows/deploy.yml in your project:
name: Deploy to Firebase Hosting
on:
push:
branches: [ main ]
jobs:
build-and-deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
- name: Install dependencies
run: npm ci
- name: Build Angular app
run: ng build --configuration production
- name: Deploy to Firebase
uses: FirebaseExtended/action-hosting-deploy@v0
with:
repoToken: '${{ secrets.GITHUB_TOKEN }}'
firebaseServiceAccount: '${{ secrets.FIREBASE_SERVICE_ACCOUNT }}'
projectId: your-project-id
target: hosting
To make this work:
- Go to Firebase Console ? Project Settings ? Service Accounts ? Generate Private Key. Save the JSON file.
- In your GitHub repo, go to Settings ? Secrets and Variables ? Actions ? New Repository Secret.
- Name it
FIREBASE_SERVICE_ACCOUNTand paste the entire contents of the JSON key.
Now, every time you push to main, GitHub will automatically build and deploy your app to Firebase.
Best Practices
Optimize Your Angular Build
Production builds should be optimized for performance. In angular.json, ensure the following settings are enabled:
- buildOptimizer: Enables advanced optimizations like tree-shaking and minification.
- optimization: Enables both script and style optimization.
- vendorChunk: Separates vendor libraries into a separate chunk for better caching.
- extractLicenses: Removes license texts from bundles to reduce size.
- sourceMap: Disable in production to reduce bundle size (keep enabled during development).
Example angular.json configuration:
"configurations": {
"production": {
"budgets": [
{
"type": "initial",
"maximumWarning": "500kb",
"maximumError": "1mb"
}
],
"buildOptimizer": true,
"optimization": true,
"vendorChunk": true,
"extractLicenses": true,
"sourceMap": false,
"namedChunks": false,
"aot": true
}
}
Enable Caching and Compression
Firebase Hosting automatically compresses assets using Brotli and Gzip. However, you can fine-tune caching headers in firebase.json for better performance:
{
"hosting": {
"public": "dist/my-angular-app",
"ignore": [
"firebase.json",
"**/.*",
"/node_modules/"
],
"headers": [
{
"source": "**/*.@(js|css)",
"headers": [
{
"key": "Cache-Control",
"value": "public, max-age=31536000"
}
]
},
{
"source": "**/*.@(html|json|xml)",
"headers": [
{
"key": "Cache-Control",
"value": "public, max-age=600"
}
]
},
{
"source": "**/*.@(png|jpg|jpeg|gif|svg|ico)",
"headers": [
{
"key": "Cache-Control",
"value": "public, max-age=31536000"
}
]
}
],
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
]
}
}
This configuration:
- Caches JavaScript and CSS files for 1 year (ideal for hashed filenames).
- Caches HTML and JSON files for 10 minutes (to allow quick updates).
- Caches images for 1 year.
- Ensures all routes fall back to
index.htmlfor client-side routing.
Use Service Workers for Offline Support
Angulars @angular/pwa package adds a service worker to your app, enabling offline functionality and background sync. Install it with:
ng add @angular/pwa
This generates a ngsw-config.json file and registers the service worker in main.ts. Firebase Hosting automatically serves the service worker file. Verify its working by opening Chrome DevTools ? Application ? Service Workers.
Minimize Bundle Size
Large bundles increase load times and hurt Core Web Vitals. Use the following techniques:
- Use lazy loading for feature modules:
loadChildren: () => import('./feature/feature.module').then(m => m.FeatureModule) - Remove unused third-party libraries.
- Use Angulars
ng build --stats-jsonto analyze bundle composition with tools like webpack-bundle-analyzer. - Optimize images using tools like
sharporsquoosh.
Monitor Performance and Errors
Integrate Firebase Performance Monitoring and Crashlytics to track app speed and errors in production:
- Install Firebase Performance Monitoring:
ng add @angular/fire - Initialize it in
app.module.tswithprovidePerformance(). - View metrics in Firebase Console ? Performance.
This helps identify slow routes, network requests, and rendering bottlenecks.
Secure Your Deployment
Never commit sensitive data like API keys to version control. Use environment variables:
- Create
src/environments/environment.prod.tswith production API endpoints. - Use
ng build --configuration productionto inject the correct values. - For secrets (e.g., Firebase API keys), use Firebases server-side functions or environment variables in Firebase Hosting via
firebase functions:config:setif needed.
Tools and Resources
Essential Tools
- Angular CLI: The standard toolchain for building, testing, and serving Angular apps. angular.io/cli
- Firebase CLI: Command-line interface for managing Firebase projects. firebase.google.com/docs/cli
- Webpack Bundle Analyzer: Visualizes bundle composition to identify large dependencies. Install with
npm install -g webpack-bundle-analyzerand runng build --stats-json && webpack-bundle-analyzer dist/*/stats.json. - Lighthouse: Chrome DevTools audit tool for performance, accessibility, and SEO. Run from DevTools ? Lighthouse tab.
- Google PageSpeed Insights: Analyzes real-world performance of your deployed site. pagespeed.web.dev
- Netlify (Alternative): If Firebase doesnt meet your needs, Netlify offers similar features with different build configurations.
Documentation and References
- Angular Deployment Guide Official documentation on building and deploying Angular apps.
- Firebase Hosting Documentation Complete reference for configuration, caching, and custom domains.
- Firebase CLI Reference All available commands and flags.
- GitHub Action for Firebase Official integration for CI/CD.
- Angular Firebase Tutorials Community-driven guides and best practices.
Community and Support
While Firebase does not offer direct customer support for free-tier users, the following resources are invaluable:
- Stack Overflow: Search for tags like
angularandfirebase-hosting. - GitHub Issues: Report bugs or request features for Firebase CLI or Angular tools.
- Reddit (r/Angular, r/Firebase): Real-time discussions and troubleshooting.
- Angular Fireside Chats: Live streams and Q&A sessions hosted by the Angular team.
Real Examples
Example 1: Personal Portfolio Site
A developer builds a single-page Angular portfolio with routing for projects, about, and contact sections. They use ng build --prod to generate the static output, then deploy via firebase deploy. The site is hosted on https://portfolio-john.web.app.
They configure caching headers in firebase.json to cache CSS/JS for 1 year and HTML for 10 minutes. They also enable the Angular service worker so the site works offline on mobile devices. After 30 days, they update the portfolio and push to GitHub, triggering an automated deployment via GitHub Actions.
Example 2: E-Commerce Landing Page
A startup creates a marketing landing page using Angular for dynamic animations and form validation. The app is small (under 200KB gzipped) and hosted on Firebase. They use a custom domain (shop.example.com) and configure redirects from www.shop.example.com to the non-www version.
They integrate Firebase Analytics to track user interactions and Firebase Performance Monitoring to measure load times. After noticing slow image loading, they convert PNGs to WebP format and add loading="lazy" attributes. PageSpeed score improves from 78 to 94.
Example 3: Internal Admin Dashboard
An enterprise team builds an internal Angular dashboard for monitoring API metrics. The app is not public-facing but requires secure, fast access for employees.
They deploy to Firebase Hosting with a custom domain and enable Firebase Authentication to restrict access. They use Firebase Rules to ensure only authenticated users can access the site. The app is built with lazy-loaded modules and code-splitting to reduce initial load time. They monitor performance daily and receive alerts for slow routes via Firebase Console.
Example 4: Open-Source Project
An open-source Angular library includes a documentation site built with Angular. The site is hosted on Firebase and automatically deployed on every release using GitHub Actions. The CI pipeline runs tests, builds the docs, and deploys to Firebase. Contributors can preview changes via Firebases preview URLs before merging.
FAQs
Can I host an Angular app with server-side rendering (SSR) on Firebase Hosting?
Firebase Hosting is designed for static sites. If you need SSR (e.g., for SEO), use Firebase Cloud Functions with Angular Universal. You can deploy a Node.js server that renders pages on the fly. This requires a different setup than static hosting and increases costs slightly.
How much does Firebase Hosting cost?
Firebase Hosting offers a generous free tier: 10 GB storage, 360 GB bandwidth/month, and 200 daily deploys. Most small to medium Angular apps stay well within these limits. Paid plans start at $25/month for higher bandwidth and additional features like custom SSL certificates on custom domains (though SSL is free on Firebase).
Why is my Angular app loading slowly on Firebase?
Common causes include:
- Unoptimized build (missing
--prodflag) - Large, unminified JavaScript bundles
- Missing caching headers
- Uncompressed assets (images, fonts)
- Network latency due to geographic distance from Firebase edge locations
Use Lighthouse or PageSpeed Insights to diagnose. Optimize assets, enable caching, and use lazy loading.
Can I use Firebase Hosting with multiple environments (dev, staging, prod)?
Yes. Use Firebase projects for each environment (e.g., myapp-dev, myapp-staging, myapp-prod). Use firebase use --add to alias them. Then deploy with firebase deploy --project myapp-staging. You can also use environment-specific angular.json configurations.
What happens if I delete my Firebase project?
Deleting a project permanently removes all hosted files, Firebase Authentication data, and associated services. The domain (e.g., your-project-id.web.app) becomes unavailable for reuse. Always backup your source code and ensure your app is deployed from version control before deleting.
How do I clear Firebase Hosting cache after a deployment?
Firebase Hosting automatically invalidates the CDN cache on every successful deployment. You do not need to manually clear it. If you suspect caching issues, append a query parameter to your URL (e.g., ?v=2) or hard-refresh your browser (Ctrl+Shift+R).
Does Firebase Hosting support HTTPS?
Yes. Firebase Hosting automatically provisions and renews free SSL certificates via Lets Encrypt for all default and custom domains. HTTPS is enforced by default.
Can I host multiple Angular apps on one Firebase project?
Yes. You can deploy multiple hosting targets in one project by defining multiple sites in firebase.json. Each site gets its own URL and configuration. Use firebase target:apply hosting myapp1 dist/app1 and firebase target:apply hosting myapp2 dist/app2 to configure multiple targets.
How do I debug deployment errors?
Run firebase deploy --debug for verbose output. Check the Firebase Console ? Hosting ? Deployments tab for error logs. Common issues include:
- Incorrect output path in
firebase.json - Missing
index.htmlin the build folder - Invalid Firebase project ID
- Network connectivity issues during upload
Conclusion
Hosting an Angular application on Firebase is a powerful, streamlined approach that combines the performance of a global CDN with the simplicity of static site deployment. By following the steps outlined in this guidefrom initializing Firebase, building your Angular app in production mode, configuring caching headers, to automating deployments with CI/CDyou can deliver fast, secure, and scalable web applications to users around the world.
The integration of Firebase Hosting with Angulars tooling ecosystem is seamless, and the platforms automatic SSL, global caching, and free tier make it ideal for both personal projects and enterprise applications. Best practices such as optimizing bundle sizes, enabling service workers, and monitoring performance ensure your app not only loads quickly but also provides a reliable, offline-capable experience.
As web applications continue to evolve toward more dynamic, user-centric experiences, the combination of Angulars component-based architecture and Firebases serverless hosting model remains one of the most compelling stacks for modern development. Whether youre launching your first app or scaling a complex dashboard, Firebase Hosting provides the infrastructure to support your ambitions without the overhead of managing servers.
Start small, test thoroughly, and iterate often. With Firebase, your next Angular app is just a few commands away from going liveglobally, securely, and at scale.