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 powerful static hosting solution optimized for single-page applications (SPAs) like those built with Angular. With seamless integration, automatic SSL certificates
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 powerful static hosting solution optimized for single-page applications (SPAs) like those built with Angular. With seamless integration, automatic SSL certificates, global CDN distribution, and easy CI/CD pipelines, Firebase Hosting has become the go-to choice for Angular developers seeking fast, reliable, and secure deployment.
This guide provides a comprehensive, step-by-step walkthrough on how to host an Angular app on Firebasefrom setting up your project to optimizing performance and troubleshooting common issues. Whether you're a beginner deploying your first Angular app or an experienced developer looking to refine your workflow, this tutorial covers everything you need to know to successfully host your application on Firebase with best practices and real-world examples.
Step-by-Step Guide
Prerequisites
Before you begin, ensure you have the following installed and configured on your development machine:
- Node.js and npm: Angular requires Node.js version 18 or higher. Verify your installation by running
node -vandnpm -vin your terminal. - Angular CLI: Install the Angular command-line interface globally using
npm install -g @angular/cli. - Firebase CLI: Install Firebase tools via npm with
npm install -g firebase-tools. - Firebase Account: Create a free account at firebase.google.com.
Once these are in place, youre ready to proceed with deploying your Angular application.
Step 1: Create or Prepare Your Angular Project
If you dont already have an Angular project, create one using the Angular CLI:
ng new my-angular-app
cd my-angular-app
Follow the prompts to configure your project (e.g., routing, CSS preprocessor). Once created, navigate into the project directory.
If youre working with an existing Angular project, ensure it builds successfully by running:
ng build --prod
This command generates an optimized production build in the dist/ folder (or dist/your-project-name depending on your Angular version). The output includes minified JavaScript, CSS, HTML, and asset files optimized for performance.
Step 2: Initialize Firebase in Your Project
Open your terminal in the root directory of your Angular project and run:
firebase login
This opens a browser window prompting you to sign in to your Firebase account. After authentication, return to the terminal. Youll see a confirmation message indicating youre logged in.
Next, initialize Firebase in your project:
firebase init
The CLI will guide you through a series of prompts:
- Select Hosting using the spacebar (you can also select other services like Firestore or Authentication if needed, but for this guide, focus on Hosting).
- Choose Use an existing project if youve already created a Firebase project, or Create a new project if you havent. If creating a new project, enter a unique project ID and follow the prompts in the browser.
- Select the public directory. For Angular apps, this is typically
dist/your-project-name. Confirm the path matches your build output. - When asked if you want to configure as a single-page app, select Yes. This ensures Firebase serves
index.htmlfor all routes, which is essential for Angulars client-side routing. - Answer No to the question about overwriting
index.htmlunless you want to replace it with Firebases default page.
After completing the setup, Firebase creates two key files in your project root:
- firebase.json: Configuration file defining hosting settings, rewrites, headers, and more.
- .firebaserc: Stores your project aliases and Firebase project IDs for easy switching between environments.
Step 3: Configure firebase.json for Angular
Open the firebase.json file and ensure its configured correctly for Angular. A typical configuration looks like this:
{
"hosting": {
"public": "dist/my-angular-app",
"ignore": [
"firebase.json",
"**/.*",
"/node_modules/"
],
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
],
"headers": [
{
"source": "**/*.@(js|css)",
"headers": [
{
"key": "Cache-Control",
"value": "public, max-age=31536000"
}
]
},
{
"source": "**/*.@(png|jpg|jpeg|gif|svg)",
"headers": [
{
"key": "Cache-Control",
"value": "public, max-age=2592000"
}
]
},
{
"source": "index.html",
"headers": [
{
"key": "Cache-Control",
"value": "public, max-age=0"
}
]
}
]
}
}
Key configuration points:
- public: Must point to the directory where
ng build --prodoutputs your files. For Angular 16+, this is usuallydist/your-project-name/browser. For older versions, itsdist/your-project-name. - rewrites: The rewrite rule
"source": "**", "destination": "/index.html"ensures that all routes (e.g.,/about,/dashboard) are served theindex.htmlfile, allowing Angular Router to handle navigation client-side. - headers: Sets aggressive caching for static assets (JS, CSS, images) to improve performance and reduce bandwidth costs. The
index.htmlfile is cached for 0 seconds to ensure users always get the latest version after deployment.
Important: If your build output directory is different (e.g., due to custom Angular configuration), update the public field accordingly. You can verify the correct path by checking your angular.json file under projects > your-project-name > architect > build > options > outputPath.
Step 4: Build Your Angular App for Production
Before deploying, always build your app in production mode:
ng build --configuration production
or, if using the older syntax:
ng build --prod
This command:
- Minifies JavaScript and CSS files
- Removes development-only code and console logs
- Enables ahead-of-time (AOT) compilation
- Generates hashed filenames for cache busting
After the build completes, verify the contents of your output directory (e.g., dist/my-angular-app) to ensure all necessary files are present: index.html, main.*.js, polyfills.*.js, styles.*.css, and asset folders like assets/.
Step 5: Deploy to Firebase Hosting
Once your build is complete and your firebase.json is configured, deploy your app with a single command:
firebase deploy
Firebase will:
- Upload all files from your public directory
- Apply the rewrite and header rules
- Provision a secure HTTPS URL
Upon successful deployment, youll see output similar to:
=== Deploying to 'your-project-id'...
i deploying hosting
i hosting: preparing dist/my-angular-app directory for upload...
? hosting: 24 files uploaded successfully
? Deployment complete!
Hosting URL: https://your-project-id.web.app
Visit the provided URL in your browser to view your live Angular application. You now have a fully hosted, production-ready app on Firebase Hosting.
Step 6: Set Up a Custom Domain (Optional)
To use your own domain (e.g., www.yourwebsite.com), follow these steps:
- In the Firebase Console, go to Hosting > Add custom domain.
- Enter your domain name and click Continue.
- Firebase will provide DNS records (CNAME or A records) that you must add to your domain registrars DNS settings (e.g., GoDaddy, Cloudflare, Namecheap).
- Wait up to 2448 hours for DNS propagation. Firebase will automatically issue and install an SSL certificate once the domain is verified.
- Once verified, your site will be accessible via your custom domain with HTTPS enabled.
For best results, use a domain registrar that supports DNS management and offers fast propagation. Cloudflare is recommended for advanced users due to its performance optimization and caching features.
Best Practices
Use Environment-Specific Configurations
Avoid hardcoding API keys or environment variables in your Angular app. Instead, leverage Angulars built-in environment system. Create separate environment files:
src/environments/environment.tsDevelopmentsrc/environments/environment.prod.tsProduction
In your environment.prod.ts, define production URLs:
export const environment = {
production: true,
apiUrl: 'https://your-api-domain.com/v1'
};
Then, in your Angular services, inject the environment:
import { environment } from '../environments/environment';
@Injectable({
providedIn: 'root'
})
export class ApiService {
private readonly baseUrl = environment.apiUrl;
}
When you run ng build --configuration production, Angular automatically replaces the environment with the production version, ensuring your Firebase-hosted app communicates with the correct backend.
Enable Compression and Brotli
Firebase Hosting automatically compresses files using Gzip. For even better performance, enable Brotli compression by adding this to your firebase.json:
"hosting": {
"public": "dist/my-angular-app",
"ignore": ["firebase.json", "/.*", "/node_modules/**"],
"rewrites": [{ "source": "**", "destination": "/index.html" }],
"headers": [...],
"compression": true
}
While Firebase enables compression by default, explicitly setting "compression": true ensures its active even if defaults change. Brotli typically reduces file sizes by 1525% compared to Gzip, significantly improving load times.
Implement Cache Busting
Angular CLI automatically appends hashes to filenames during production builds (e.g., main.abc123.js). This ensures users always receive the latest version of your assets after deployment.
Verify that your angular.json has "outputHashing": "all" under the production build configuration:
"configurations": {
"production": {
"outputHashing": "all",
...
}
}
This prevents browser caching issues and ensures users dont see stale content after updates.
Optimize Performance with Preloading
Use Angulars built-in lazy loading and preloading strategies to improve perceived performance. In your app-routing.module.ts, configure preloading:
import { PreloadAllModules } from '@angular/router';
@NgModule({
imports: [RouterModule.forRoot(routes, {
preloadingStrategy: PreloadAllModules
})],
exports: [RouterModule]
})
export class AppRoutingModule { }
This strategy loads lazy-loaded modules in the background after the initial route loads, reducing perceived wait time for subsequent navigation.
Monitor and Analyze Performance
Use Firebase Hostings built-in analytics and Googles Lighthouse tool to monitor performance:
- Access your Firebase Hosting dashboard to view traffic, bandwidth usage, and deployment history.
- Run Lighthouse audits in Chrome DevTools (
Ctrl+Shift+I> Lighthouse) to identify performance bottlenecks. - Use tools like Web Vitals to track Core Web Vitals (LCP, FID, CLS) and ensure compliance with Googles ranking factors.
Optimize critical assets: compress images with WebP, defer non-critical JavaScript, and inline critical CSS for above-the-fold content.
Secure Your App
Firebase Hosting provides HTTPS by default, but you can enhance security further:
- Enable HTTP Strict Transport Security (HSTS) by adding a header in
firebase.json:
{
"source": "**",
"headers": [
{
"key": "Strict-Transport-Security",
"value": "max-age=63072000; includeSubDomains; preload"
}
]
}
- Use Content Security Policy (CSP) headers to mitigate XSS attacks:
{
"source": "**",
"headers": [
{
"key": "Content-Security-Policy",
"value": "default-src 'self'; script-src 'self' https://cdn.jsdelivr.net; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' https://fonts.gstatic.com;"
}
]
}
Adjust the CSP rules based on your apps external dependencies (e.g., Google Fonts, analytics scripts).
Version Control and Deployment Automation
Always commit your firebase.json and .firebaserc files to version control (e.g., Git), but exclude the dist/ folder. Add it to your .gitignore:
dist/
node_modules/
Use GitHub Actions, GitLab CI, or Bitbucket Pipelines to automate deployments. Example GitHub Actions workflow:
name: Deploy to Firebase
on:
push:
branches: [ main ]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: '18'
- run: npm ci
- run: ng build --configuration production
- uses: FirebaseExtended/action-hosting-deploy@v0
with:
repoToken: '${{ secrets.GITHUB_TOKEN }}'
firebaseServiceAccount: '${{ secrets.FIREBASE_SERVICE_ACCOUNT }}'
projectId: your-project-id
channelId: live
This workflow automatically deploys your app to Firebase whenever you push to the main branch, enabling seamless CI/CD.
Tools and Resources
Firebase Console
The Firebase Console is your central hub for managing hosting deployments, viewing analytics, setting up custom domains, and monitoring performance. It provides real-time logs, deployment history, and bandwidth usage statistics.
Firebase CLI
The Firebase Command Line Interface (CLI) is essential for local development and deployment. It supports commands like:
firebase loginAuthenticate your accountfirebase initSet up hosting configurationfirebase deployDeploy your appfirebase serveTest your app locally before deployingfirebase hosting:channel:deployDeploy to preview channels for staging
Install and update the CLI regularly:
npm install -g firebase-tools
Angular CLI
The Angular CLI streamlines development, testing, and building. Key commands:
ng newCreate a new projectng generate componentCreate componentsng build --prodBuild for productionng serveRun local development server
Google Lighthouse
Integrated into Chrome DevTools, Lighthouse provides performance, accessibility, SEO, and best practice audits. Run audits on your Firebase-hosted URL to identify optimization opportunities.
Web Vitals Extension
The Chrome extension Web Vitals displays real-time Core Web Vitals metrics as you browse your site, helping you monitor user experience in production.
Netlify and Vercel Comparison
While Firebase Hosting is excellent for Angular apps, developers often compare it with Netlify and Vercel. Key differentiators:
- Firebase: Tight integration with Google services, free tier generous for small apps, excellent for apps using Firebase Auth/Firestore.
- Netlify: Strong form handling, serverless functions, and simpler CI/CD for non-Google ecosystems.
- Vercel: Optimized for Next.js, but also supports Angular with excellent preview deployments.
Firebase remains the top choice for Angular developers already using Googles ecosystem due to unified authentication, real-time databases, and analytics.
Third-Party Tools
- Angular Console: GUI for Angular CLI (optional, helpful for beginners).
- Visual Studio Code: Recommended editor with extensions for Angular, Firebase, and JSON.
- Postman: For testing API endpoints if your app communicates with external services.
Real Examples
Example 1: Personal Portfolio Website
A developer builds an Angular portfolio app with routing for About, Projects, and Contact pages. After building with ng build --prod, they configure firebase.json to rewrite all routes to index.html and enable Brotli compression. They deploy via firebase deploy and receive a URL like https://portfolio-123.web.app. They then connect a custom domain www.johndoe.dev using Cloudflare DNS. The site loads in under 1.2 seconds on mobile, achieving a Lighthouse score of 98/100.
Example 2: Internal Dashboard App
A company develops an internal analytics dashboard using Angular and Firebase Authentication. The app is deployed to Firebase Hosting with a custom domain dashboard.company.com. They use Firebases hosting preview channels to test changes before merging into main. Each pull request triggers an automated deployment to a temporary URL (e.g., pr-456-abc123.web.app), allowing team members to review changes without affecting production.
Example 3: E-commerce Landing Page
A startup launches a marketing landing page built with Angular and static data. They use Firebase Hosting to serve the page globally with CDN caching. They implement aggressive caching headers for assets and use a service worker (via Angular PWA) to enable offline access. The site handles 50,000+ monthly visitors with zero downtime and 99.9% uptime.
Example 4: Open Source Project
An open-source Angular library includes a demo app. The projects GitHub repository includes a CI workflow that deploys the demo to Firebase Hosting on every merge to main. The live demo is linked in the README as https://demo.angular-lib-example.web.app, allowing users to interact with the library without installing it locally.
FAQs
Can I host multiple Angular apps on the same Firebase project?
Yes. You can configure multiple hosting sites within one Firebase project using the firebase hosting:channel command or by defining multiple hosting targets in firebase.json. Each site can have its own domain and deployment settings.
Is Firebase Hosting free?
Yes. Firebase offers a free Spark plan that includes 10 GB of storage, 360 MB/day of bandwidth, and 100 daily deploys. This is sufficient for most small to medium apps. Paid plans (Blaze) are available for higher traffic or custom domains with SSL.
Why does my Angular app show a blank page after deployment?
This is usually caused by incorrect routing or build output path. Verify that:
- The
publicpath infirebase.jsonmatches your actual build output directory. - You have the rewrite rule
"source": "**", "destination": "/index.html". - You ran
ng build --prodand notng serve. - Your base href in
index.htmlis set correctly (e.g.,<base href="/">).
How do I update my app after deployment?
Rebuild your app with ng build --prod and redeploy with firebase deploy. Firebase automatically replaces the old files with the new ones. Use versioned filenames (enabled by default) to ensure users get the latest assets.
Can I use Firebase Hosting with a backend API?
Firebase Hosting serves static files only. For a backend, integrate with Firebase Functions, Firestore, or Cloud Run. Alternatively, host your API on a separate service (e.g., AWS, Heroku) and call it via HTTP from your Angular app.
Does Firebase Hosting support server-side rendering (SSR)?
No. Firebase Hosting is a static CDN. For SSR with Angular, use Angular Universal and deploy to a Node.js environment like Google App Engine, AWS Lambda, or Vercel.
How long does DNS propagation take for a custom domain?
Typically 2448 hours, but often faster (under 1 hour) with providers like Cloudflare. Use tools like DNSChecker.org to monitor propagation status.
What happens if I exceed my bandwidth limit?
On the free plan, exceeding bandwidth results in your site becoming unavailable until the next billing cycle. Upgrade to the Blaze plan for pay-as-you-go pricing and unlimited bandwidth.
Conclusion
Hosting an Angular application on Firebase is a streamlined, reliable, and scalable solution that combines the power of Googles infrastructure with the flexibility of modern web development. By following the steps outlined in this guidefrom setting up your project and configuring firebase.json to deploying with best practices and monitoring performanceyou can ensure your Angular app loads quickly, securely, and globally.
Firebase Hosting eliminates the complexity of server management, provides automatic HTTPS, and integrates seamlessly with Angulars build pipeline. Whether youre launching a personal project, a business dashboard, or an open-source demo, Firebase offers the tools to get your app online with minimal friction.
Remember to prioritize performance optimization, secure your app with proper headers, automate deployments via CI/CD, and continuously monitor user experience with tools like Lighthouse and Web Vitals. As you grow, consider leveraging Firebases other servicesAuthentication, Firestore, and Cloud Functionsto build a complete backend without managing infrastructure.
With this comprehensive guide, you now have the knowledge and confidence to host any Angular application on Firebaseefficiently, professionally, and at scale.