Comprehensive Guide: Deploying a Flutter Web App to Firebase Hosting Using GitHub Actions

Comprehensive Guide: Deploying a Flutter Web App to Firebase Hosting Using GitHub Actions

A Step-by-Step Guide to Automating Flutter Web App Deployments with Firebase Hosting and GitHub Actions

Deploying a Flutter web app to Firebase Hosting using GitHub Actions streamlines the process of keeping your web application live and up-to-date. This guide will walk you through the essentials of setting up Firebase Hosting, configuring GitHub Actions for continuous deployment, and ensuring your deployment runs smoothly. Whether you want to automate your workflow or integrate deployment into your development process, this guide covers everything you need to start.

Prerequisites

Before you start, ensure you have the following:

  1. Flutter Installed: Download and install Flutter from flutter.dev.

  2. Firebase CLI: Install Firebase CLI using npm:

     npm install -g firebase-tools
    
  3. GitHub Repository: Your Flutter web project should be hosted on GitHub.

  4. Firebase Project: You need a Firebase project created in the Firebase Console.

Set Up Firebase Hosting

Initialize Firebase in Your Project

  1. Navigate to Your Project Directory: Open your terminal and go to your Flutter project directory:

     cd path/to/your/flutter/project
    
  2. Initialize Firebase: Run the Firebase CLI command to initialize Firebase Hosting:

     firebase init
    

    Follow the prompts:

    • Hosting: Select Firebase Hosting.

    • Public Directory: Enter build/web (this is the directory where Flutter builds the web app).

    • Single-Page App: Choose Yes to configure as a single-page app (rewrite all URLs to /index.html).

    • Automatic Builds with GitHub: If prompted, choose whether to set up automatic builds and deploys with GitHub Actions.

Configure Firebase Hosting

  1. Edit firebase.json: Ensure your firebase.json configuration file looks like this:

     {
       "flutter": {
         "platforms": {
           "dart": {
             "lib/firebase_options.dart": {
               "projectId": "<project-id>",
               "configurations": {
                 "web": "<appId>" // this is found on firebase_options
               }
             }
           }
         }
       },
       "hosting": {
         "public": "build/web",
         "ignore": [
           "firebase.json",
           "**/.*",
           "**/node_modules/**"
         ]
       }
     }
    
  2. Optional: Configure firebaserc: You might also need a .firebaserc file for project aliasing:

     {
       "projects": {
         "default": "your-project-id"
       }
     }
    

Add Firebase Configuration

  1. Generate Firebase Config File: Make sure you have a firebase_config file (e.g., firebase_options.dart) configured in your Flutter project. This file is usually auto-generated when you initialize Firebase.

  2. Add Firebase to Your Flutter App: Integrate Firebase into your Flutter project by importing the generated configuration file and initializing Firebase in your main.dart.

  3. Integrate Firebase: Import the configuration and initialize Firebase in main.dart:

     import 'package:firebase_core/firebase_core.dart';
     import 'firebase_options.dart';
    
     void main() async {
       WidgetsFlutterBinding.ensureInitialized();
       await Firebase.initializeApp(
         options: DefaultFirebaseOptions.currentPlatform,
       );
       runApp(MyApp());
     }
    

Configure GitHub Actions

Create GitHub Actions Workflow File

  1. Create Workflow File: In your GitHub repository, create a new workflow file at .github/workflows/firebase-hosting.yml. Below is a sample configuration:

     name: Deploy to Firebase Hosting
    
     on:
       push:
         branches:
           - main  # Replace with your default branch
       pull_request:
         branches:
           - main # Replace with your default branch
    
     jobs:
       build_and_deploy:
         runs-on: ubuntu-latest
    
         steps:
         - name: Checkout Repository
           uses: actions/checkout@v2
    
         - name: Set up Flutter
           uses: subosito/flutter-action@v3
           with:
             flutter-version: '3.24.1'  # Specify the Flutter version
    
         - name: Install Dependencies
           run: flutter pub get
    
         - name: Build Flutter Web
           run: flutter build web --release
    
         - name: Set up Node.js
           uses: actions/setup-node@v3
           with:
             node-version: '18'  # Ensure compatibility with Firebase CLI
    
         - name: Install Firebase CLI
           run: npm install -g firebase-tools
    
         - name: Deploy to Firebase Hosting
           run: firebase deploy --only hosting --project <firebase-project-id>
           env:
             FIREBASE_TOKEN: ${{ secrets.FIREBASE_TOKEN }}
    

Set Up Firebase Token

  1. Generate Firebase Token: Authenticate with Firebase CLI and generate a token:

     firebase login:ci
    
  2. Add Token to GitHub Secrets:

    • Go to your GitHub repository.

    • Navigate to Settings > Secrets and variables > Actions.

    • Click New repository secret.

    • Name it FIREBASE_TOKEN and paste the generated token.

Managing Secrets and Environment Variables

  1. Add Environment Variables: Add additional environment variables if needed:

     name: Set up Environment Variables
       run: echo "VARIABLE_NAME=value" >> $GITHUB_ENV
    
  2. Use Secrets in Workflow: Reference secrets directly in your workflow file:

     env:
       API_KEY: ${{ secrets.API_KEY }}
    

Validate and Monitor

Commit and Push Changes

  1. Commit Workflow File: Add and commit your workflow configuration:

     git add .github/workflows/firebase-hosting.yml
     git commit -m "Add GitHub Actions workflow for Firebase Hosting"
    
  2. Push to GitHub: Push your changes to the remote repository:

     git push origin main
    

Monitor Workflow Execution

  1. Access Actions Tab:

    • Go to the "Actions" tab in your GitHub repository.

    • Monitor the build and deployment process to ensure it is completed successfully.

Verify Deployment

  1. Check Firebase Console:

    • Visit the Firebase Console.

    • Select your project and navigate to Hosting.

    • Find the Live URL or Site URL where your app is deployed.

  2. Visit the Deployed URL:

    • The URL typically follows this pattern:

        https://your-project-id.web.app
      

      or

        https://your-project-id.firebaseapp.com
      

Advanced Configuration

Custom Build Scripts

  1. Modify Build Commands: If you have custom build requirements, modify the flutter build command in the workflow file:

     name: Build Flutter Web
       run: flutter build web --release --web-renderer html
    
  2. Add Pre-Build Steps: Include additional steps before building:

     name: Pre-build Steps
       run: ./scripts/pre_build.sh
    

Managing Multiple Environments

  1. Configure Multiple Environments: Use different Firebase projects for staging and production:

     name: Deploy to Firebase Hosting
       run: firebase deploy --only hosting --project ${{ secrets.FIREBASE_PROJECT }}
       env:
         FIREBASE_TOKEN: ${{ secrets.FIREBASE_TOKEN }}
    
  2. Set Environment-Specific Secrets: Add environment-specific secrets for different Firebase projects.

Common Issues and Troubleshooting

Project Not Set

  • Error Message: No currently active project

  • Solution: Ensure you set the project correctly. Use:

      firebase use --add
    

    Set the alias (e.g., staging) and use it in your GitHub Actions workflow.

Deprecation Warnings

  • Warnings: Methods or variables deprecated in index.html.

  • Solution: Update index.html:

    • Replace serviceWorkerVersion with {{flutter_service_worker_version}}.

    • Replace FlutterLoader.loadEntrypoint with FlutterLoader.load.

Node.js Version Incompatibility

  • Error Message: Firebase CLI version incompatible with Node.js version.

  • Solution: Ensure your Node.js version is compatible. Update to Node.js 18 or newer:

      - name: Set up Node.js
        uses: actions/setup-node@v3
        with:
          node-version: '18'
    

Firebase CLI Errors

  • Error Message: Issues with Firebase CLI during deployment.

  • Solution: Ensure Firebase CLI is installed correctly and up-to-date. Check your workflow configuration for accuracy.

Optimize Build Times

  1. Cache Dependencies: Use caching strategies in your workflow to speed up builds:

     name: Cache Flutter Dependencies
       uses: actions/cache@v3
       with:
         path: ~/.pub-cache
         key: ${{ runner.os }}-pub-cache-${{ github.sha }}
         restore-keys: |
           ${{ runner.os }}-pub-cache-
    
  2. Minimize Build Steps: Remove unnecessary build steps to reduce build times.

Monitor and Rollback Deployments

  1. Monitor Performance: Use Firebase Console to monitor deployment performance and errors.

  2. Rollback If Needed: If issues arise, use Firebase Console to roll back to a previous deployment.

Conclusion

By following this comprehensive guide, you can automate the deployment of your Flutter web app to Firebase Hosting using GitHub Actions. This setup ensures that your web app is continuously integrated and deployed with minimal manual intervention. Regularly monitor your deployment processes and Firebase Console for optimal results.

For further details, consult the Flutter documentation, Firebase Hosting documentation, or Firebase For Flutter Web to stay updated with best practices and additional features.


Did you find this article valuable?

Support Flutter Aware by becoming a sponsor. Any amount is appreciated!

ย