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:
Flutter Installed: Download and install Flutter from flutter.dev.
Firebase CLI: Install Firebase CLI using npm:
npm install -g firebase-tools
GitHub Repository: Your Flutter web project should be hosted on GitHub.
Firebase Project: You need a Firebase project created in the Firebase Console.
Set Up Firebase Hosting
Initialize Firebase in Your Project
Navigate to Your Project Directory: Open your terminal and go to your Flutter project directory:
cd path/to/your/flutter/project
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
Edit
firebase.json
: Ensure yourfirebase.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/**" ] } }
Optional: Configure
firebaserc
: You might also need a.firebaserc
file for project aliasing:{ "projects": { "default": "your-project-id" } }
Add Firebase Configuration
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.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
.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
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
Generate Firebase Token: Authenticate with Firebase CLI and generate a token:
firebase login:ci
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
Add Environment Variables: Add additional environment variables if needed:
name: Set up Environment Variables run: echo "VARIABLE_NAME=value" >> $GITHUB_ENV
Use Secrets in Workflow: Reference secrets directly in your workflow file:
env: API_KEY: ${{ secrets.API_KEY }}
Validate and Monitor
Commit and Push Changes
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"
Push to GitHub: Push your changes to the remote repository:
git push origin main
Monitor Workflow Execution
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
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.
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
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
Add Pre-Build Steps: Include additional steps before building:
name: Pre-build Steps run: ./scripts/pre_build.sh
Managing Multiple Environments
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 }}
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
withFlutterLoader.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
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-
Minimize Build Steps: Remove unnecessary build steps to reduce build times.
Monitor and Rollback Deployments
Monitor Performance: Use Firebase Console to monitor deployment performance and errors.
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.