TechLead
Lesson 6 of 8
8 min read
Firebase

Firebase Hosting - Deploy & Host Web Apps with Global CDN

Learn how to deploy and host web applications with Firebase Hosting. Free SSL, global CDN, one-command deploy, custom domains, preview channels, CI/CD with GitHub Actions, and instant rollbacks.

What is Firebase Hosting?

Firebase Hosting provides fast and secure hosting for your web app, static and dynamic content, and microservices. Content is served over an SSL connection from the closest edge server on Google's global CDN.

With zero configuration, you can deploy web apps and serve both static and dynamic content to a global CDN with a single command. You can also pair Firebase Hosting with Cloud Functions to build and host full-stack applications.

🚀 Key Features

  • 🔒 Free SSL: Automatic SSL certificates for custom domains.
  • 🌐 Global CDN: Content delivered from edge servers worldwide.
  • ⚡ One-Command Deploy: Deploy with a single CLI command.
  • 🔄 Instant Rollback: Roll back to previous versions instantly.
  • 🎯 Preview URLs: Share previews before going live.

Setting Up Firebase Hosting

Get started with Firebase Hosting using the CLI:

# Install Firebase CLI globally
npm install -g firebase-tools

# Login to Firebase
firebase login

# Initialize hosting in your project directory
firebase init hosting

During initialization, you'll be asked:

  • Select a Firebase project (or create a new one)
  • Specify your public directory (e.g., "build", "dist", "public")
  • Configure as a single-page app (rewrite all URLs to /index.html)?
  • Set up automatic builds with GitHub?

firebase.json Configuration

The firebase.json file configures your hosting settings:

{
  "hosting": {
    "public": "build",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
  }
}

Deploying Your Site

Deploy your application to Firebase Hosting:

# Build your app first (if needed)
npm run build

# Deploy to Firebase
firebase deploy --only hosting

# Deploy everything (hosting + functions + rules)
firebase deploy

$ firebase deploy --only hosting

=== Deploying to 'my-project'...

i deploying hosting

i hosting[my-project]: beginning deploy...

i hosting[my-project]: found 42 files in build

✓ hosting[my-project]: file upload complete

✓ Deploy complete!

Hosting URL: https://my-project.web.app

Custom Domain Setup

Connect your own domain to Firebase Hosting:

# Add custom domain via CLI
firebase hosting:channel:deploy --only hosting

# Or use the Firebase Console:
# 1. Go to Hosting in Firebase Console
# 2. Click "Add custom domain"
# 3. Enter your domain name
# 4. Verify ownership (TXT record)
# 5. Point your domain to Firebase (A records)

DNS Records for Custom Domain

# Add these A records to your DNS:
@ A 151.101.1.195
@ A 151.101.65.195

# For www subdomain, add a CNAME:
www CNAME your-project.web.app

Preview Channels

Create preview URLs to test changes before deploying to production:

# Create a preview channel
firebase hosting:channel:deploy preview-name

# Example output:
# Channel URL: https://my-project--preview-name-abc123.web.app

# Preview channels expire after 7 days by default
# Set custom expiration:
firebase hosting:channel:deploy preview-name --expires 30d

# List all channels
firebase hosting:channel:list

# Delete a channel
firebase hosting:channel:delete preview-name

URL Rewrites

Configure rewrites for SPAs and dynamic routes:

{
  "hosting": {
    "rewrites": [
      // Rewrite all requests to index.html (SPA)
      {
        "source": "**",
        "destination": "/index.html"
      },

      // Rewrite to a Cloud Function
      {
        "source": "/api/**",
        "function": "api"
      },

      // Rewrite to Cloud Run
      {
        "source": "/backend/**",
        "run": {
          "serviceId": "my-service",
          "region": "us-central1"
        }
      }
    ]
  }
}

Redirects

Set up URL redirects:

{
  "hosting": {
    "redirects": [
      // Simple redirect
      {
        "source": "/old-page",
        "destination": "/new-page",
        "type": 301
      },

      // Redirect with glob pattern
      {
        "source": "/blog/:post*",
        "destination": "https://blog.example.com/:post",
        "type": 302
      },

      // Redirect with regex
      {
        "source": "/users/:id(\\d+)",
        "destination": "/profile/:id",
        "type": 301
      }
    ]
  }
}

Custom Headers

Set custom headers for security and caching:

{
  "hosting": {
    "headers": [
      // Global security headers
      {
        "source": "**",
        "headers": [
          {
            "key": "X-Frame-Options",
            "value": "DENY"
          },
          {
            "key": "X-Content-Type-Options",
            "value": "nosniff"
          },
          {
            "key": "X-XSS-Protection",
            "value": "1; mode=block"
          }
        ]
      },

      // Cache static assets
      {
        "source": "**/*.@(jpg|jpeg|gif|png|svg|webp|js|css|woff2)",
        "headers": [
          {
            "key": "Cache-Control",
            "value": "public, max-age=31536000, immutable"
          }
        ]
      },

      // No cache for HTML
      {
        "source": "**/*.html",
        "headers": [
          {
            "key": "Cache-Control",
            "value": "no-cache, no-store, must-revalidate"
          }
        ]
      }
    ]
  }
}

Deploying Next.js Apps

Deploy Next.js applications with Firebase Hosting and Cloud Functions:

# For static Next.js export
# next.config.js
module.exports = {
  output: 'export',
  distDir: 'out'
};

# Build and deploy
npm run build
firebase deploy --only hosting
# For SSR Next.js (with Cloud Functions)
# Install the Firebase Next.js adapter
npm install @firebase/experimental-nextjs

# firebase.json
{
  "hosting": {
    "source": ".",
    "ignore": ["firebase.json", "**/.*", "**/node_modules/**"],
    "frameworksBackend": {
      "region": "us-central1"
    }
  }
}

# Deploy with frameworks support
firebase experiments:enable webframeworks
firebase deploy

GitHub Actions CI/CD

Set up automatic deployments with GitHub Actions:

# .github/workflows/firebase-hosting.yml
name: Deploy to Firebase Hosting

on:
  push:
    branches:
      - main
  pull_request:
    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'
          cache: 'npm'

      - name: Install dependencies
        run: npm ci

      - name: Build
        run: npm run build

      - name: Deploy to Firebase (Preview)
        if: github.event_name == 'pull_request'
        uses: FirebaseExtended/action-hosting-deploy@v0
        with:
          repoToken: '${{ secrets.GITHUB_TOKEN }}'
          firebaseServiceAccount: '${{ secrets.FIREBASE_SERVICE_ACCOUNT }}'
          projectId: your-project-id
          expires: 7d

      - name: Deploy to Firebase (Production)
        if: github.ref == 'refs/heads/main'
        uses: FirebaseExtended/action-hosting-deploy@v0
        with:
          repoToken: '${{ secrets.GITHUB_TOKEN }}'
          firebaseServiceAccount: '${{ secrets.FIREBASE_SERVICE_ACCOUNT }}'
          projectId: your-project-id
          channelId: live

Rollback Deployments

Roll back to a previous version if needed:

# List recent deployments
firebase hosting:channel:list

# View deployment history in Firebase Console
# Go to Hosting > Release History

# Rollback using CLI
firebase hosting:clone SOURCE_SITE_ID:SOURCE_CHANNEL \
  TARGET_SITE_ID:live

# Or use the Console:
# 1. Go to Hosting > Release History
# 2. Find the version you want
# 3. Click the menu (⋮) > Rollback

Multiple Sites

Host multiple sites in one Firebase project:

# Add a new site
firebase hosting:sites:create my-second-site

# firebase.json with multiple sites
{
  "hosting": [
    {
      "target": "main",
      "public": "build",
      "rewrites": [...]
    },
    {
      "target": "admin",
      "public": "admin-build",
      "rewrites": [...]
    }
  ]
}

# Set up deploy targets
firebase target:apply hosting main my-project
firebase target:apply hosting admin my-project-admin

# Deploy specific site
firebase deploy --only hosting:main
firebase deploy --only hosting:admin

💡 Key Takeaways

  • • Firebase Hosting serves content from a global CDN with free SSL
  • • Deploy with a single command: firebase deploy
  • • Use preview channels to test before going live
  • • Configure rewrites for SPAs and API routes
  • • Set up CI/CD with GitHub Actions for automatic deployments
  • • Roll back instantly to previous versions if needed

📚 Learn More

Firebase Hosting Pricing & Free Tier

Firebase Hosting includes a generous free tier (Spark plan):

  • 1 GB storage for static assets
  • 10 GB/month data transfer
  • Free SSL certificates for all domains
  • Multiple preview channels for testing
  • Custom domain support included

For most personal projects and small apps, the free tier is more than enough. The Blaze (pay-as-you-go) plan offers additional storage and bandwidth.

Firebase Hosting vs Other Platforms

How Firebase Hosting compares to popular alternatives:

Feature Firebase Hosting Vercel Netlify
Free SSL
Global CDN✅ Google CDN✅ Edge Network✅ CDN
Preview Deploys✅ Channels✅ Per Branch✅ Deploy Previews
Serverless Functions✅ Cloud Functions✅ Edge/Serverless✅ Functions
Database Integration✅ Firestore + RTDB⚠️ External⚠️ External
Auth Built-in✅ Firebase Auth✅ Identity
Free Bandwidth10 GB/mo100 GB/mo100 GB/mo

Firebase Hosting shines when your app already uses other Firebase services (Auth, Firestore, Storage). Its tight integration with the Firebase ecosystem makes it the natural choice for Firebase-powered apps.

Frequently Asked Questions

Is Firebase Hosting free?

Yes. Firebase Hosting offers a free Spark plan that includes 1 GB of storage and 10 GB of data transfer per month. Free SSL certificates and custom domain support are included on all plans. Most small to medium projects stay within the free tier.

How do I deploy to Firebase Hosting?

Install the Firebase CLI with npm install -g firebase-tools, run firebase login, initialize your project with firebase init hosting, build your app, and deploy with firebase deploy --only hosting. Your site will be live at your-project.web.app within seconds.

Can I use a custom domain with Firebase Hosting?

Yes. Go to the Firebase Console → Hosting → Add custom domain. You'll verify ownership via a TXT DNS record and then point your domain to Firebase using A records. SSL certificates are provisioned automatically and free of charge.

Does Firebase Hosting support server-side rendering (SSR)?

Yes. Firebase Hosting can be paired with Cloud Functions or Cloud Run for SSR. For Next.js apps, Firebase offers experimental framework support that handles SSR automatically. For static sites, use output: 'export' in your Next.js config.

Can I deploy a React or Next.js app to Firebase Hosting?

Absolutely. For React apps (Create React App, Vite), build your project and set the public directory to your build output folder. For static Next.js exports, set output: 'export' and deploy the out directory. For SSR Next.js, use Firebase's web frameworks support.

How fast is Firebase Hosting?

Firebase Hosting serves content from Google's global CDN edge servers, delivering sub-100ms response times worldwide. All content is served over HTTPS with HTTP/2, and static assets are automatically cached at the edge for optimal performance.

Continue Learning