Table of contents
- Why choosing Firebase hosting?
- Firebase Hosting free plan limits
- Creating a simple website to start with
- Creating our project in Firebase console website
- Installing tools and initialization
- Trying our website locally using Firebase emulator
- Deploying our website to a temporary preview channel
- Deploying our website to Firebase Hosting
- How to run a Firebase hosting predeploy script?
- Modifying the default cashing behavior of Firebase hosting
- How to use Firebase hosting with GitHub CI/CD
- How to deploy a React App using Firebase Hosting?
- How to deploy a NextJS App using Firebase Hosting?
- Conclusion
In this tutorial we will explore different Firebase hosting and emulator options, and how to using Firebase ( free services only) to host our own website, we will get a free domain: “https://your_website.web.app”
Why choosing Firebase hosting?
Firebase hosting is production-grade web content hosting for developers from Google.
With a single command, you can start deploying your web app and serve both static and dynamic content to a global CDN (content delivery network).
Firebase will automatically compress your content using gzip or Brotli, and save your content in SSDs located in different places around the world (CDN).
After deployment, you will get a free custom domain with SSl certificate.
Firebase Hosting free plan limits
Storage: 10 GB
Data transfer: 360 MB per day
Data transfer: 10GB per month
A maximum of 32 MB per file
A maximum of 1000 files per deployment
A maximum of 36 deployment per day
Creating a simple website to start with
To start, we will create a very basic website, it will contain three files (index.html, style.css and app.js) all contained in one folder: “ /public”.
/public
├─ index.html
├─ app.js
└─ style.css
index.html
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My project</title>
<script src="./app.js" defer></script>
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
<div class="container">
<h1 class="title"> Welcome to my project</h1>
<p>Welcome to this simple website</p>
<p id="status" class="status"></p>
</div>
</body>
</html>
app.js
document.getElementById("status").innerHTML = "🟢 Javascript file loaded with success";
style.css
.title {
color: navy;
}
.status {
border: 1px solid navy;
}
.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100vh;
}
Creating our project in Firebase console website
Before going on with our hosting, we must create a project first in Firebase website.
Click on: + Add project.
Enter your project name then click on: “Continue”.
- Now, you can enable or disable google analytics in this project ( you can add it later if you won’t to).
- Configure your Google analytics by choosing the right project or by creating a new one from the drop-down menu
- Check “I accept the Google Analytics terms” then click on: Create project
- A welcome page will show up
Installing tools and initialization
We will use the Firebase CLI to deploy our website (local files) to Firebase servers, After the deployment, we will get a unique URL with “.web.app” as a the top level domain (TLD).
In this tutorial we will use:
Firebase emulators: to run our website locally.
Firebase hosting: to host our website.
GitHub actions to automatically deploy.
First globally install Firebase CLI package
npm install -g firebase-tools
Login with your credentials
firebase login
Then Initialize your project
firebase init
- Select The features that you desire to include in your project, we will choose Hosting and Emulators for now.
- Select >
Use an existing project
What do you want to use as your public directory? (public)
Click enter, we will keep the default value.
What do you want to use as your public directory? public
? Configure as a single-page app (rewrite all urls to /index.html)? (y/N)
Click “y” to preserve the default value.
Set up automatic builds and deployments with GitHub? (y/N)
Click “N”, we will configure that later.
? File public/index.html already exists. Overwrite? (y/N)
Click “N” to keep our “index.html”
Now the emulator configuration
\=== Emulators Setup
? Which Firebase emulators do you want to set up? Press Space to select emulators,
then Enter to confirm your choices. (Press <space> to select, <a> to
toggle all, <i> to invert selection, and <enter> to proceed)
❯◯ Authentication Emulator
◯ Functions Emulator
◯ Firestore Emulator
◯ Database Emulator
◯ Hosting Emulator
◯ Pub/Sub Emulator
◯ Storage Emulator
Choose: Hosting Emulator
? Which port do you want to use for the hosting emulator? (5000)
Keep the default value
? Would you like to enable the Emulator UI? (Y/n)
? Would you like to enable the Emulator UI? Yes
? Which port do you want to use for the Emulator UI (leave empty to use any available port)?
? Would you like to download the emulators now? (y/N) y
Two files and one directory will be added to our project root directory
- firebase.json
witch contain Firebase configuration
{
"hosting": {
"public": "public",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
]
},
"emulators": {
"hosting": {
"port": 5000
},
"ui": {
"enabled": true,
"port": 5001
},
"singleProjectMode": true
}
}
- .firebaseserc
Witch contain our project ID
{
"projects": {
"default": "myproject-d2260"
}
}
- /.firebase
With Contain hashes for all deployed files in our project to optimize future deployment.
Trying our website locally using Firebase emulator
Before deploying our website to Firebase servers, we will use Emulate Hosting to start our project at a locally hosted URL.
firebase emulators:start --project myproject-d2260
Where “myproject-d2260” is the ID of your project, you can get it from Firebase console website or from “.firebaseserc”
From your browser, Go to this URL to start your website locally
http://127.0.0.1:5000
Deploying our website to a temporary preview channel
To view and share your changes at a temporary preview URL on the Firebase servers, we will run this command.
firebase hosting:channel:deploy beta
Where “beta” is the name of the temporary channel.
The result:
✔ hosting:channel: Channel URL (myproject-d2260): https://myproject-d2260--beta-f1m33zsv.web.app [expires 2023-03-11 16:18:25]
Where:
myproject-d2260: the project ID
beta: the preview channel name
f1m33zsv: random number generated by Firebase
[expires 2023–03–11 16:18:25]: when your URL will expire
By default this channel will expire after 7 days, to change this behavior you can add “ — expires” to our last command.
For example:
firebase hosting:channel:deploy beta --expires 1h
This channel will expire in 1 hour.
Or:
firebase hosting:channel:deploy beta --expires 10m
This channel will expire in 10 minutes.
Deploying our website to Firebase Hosting
If you are satisfied with the results, you can deploy your website with this command
firebase deploy
The result of this command
=== Deploying to 'myproject-d2260'...
i deploying hosting
i hosting[myproject-d2260]: beginning deploy...
i hosting[myproject-d2260]: found 3 files in public
✔ hosting[myproject-d2260]: file upload complete
i hosting[myproject-d2260]: finalizing version...
✔ hosting[myproject-d2260]: version finalized
i hosting[myproject-d2260]: releasing new version...
✔ hosting[myproject-d2260]: release complete
✔ Deploy complete!
Project Console: https://console.firebase.google.com/project/myproject-d2260/overview
Hosting URL: https://myproject-d2260.web.app
You website URL:
https://myproject-d2260.web.app
If anything goes wrong, you can undo this deployment with one click in Firebase console website, you can rollback or delete up to five deployment.
How to run a Firebase hosting predeploy script?
To run a predeploy script before our deployment workflow, add this line to “firebase.json” with the name of the script.
"predeploy": "script_name",
We can use it for example to copy some files, minify JavaScript files or to run a build script ( for ReactJS or NextJS), before starting the deployment process.
Modifying the default cashing behavior of Firebase hosting
The default Cache-Control header value for Firebase Hosting is max-age=600, which means that the browser and any intermediate caches (e.g. CDN) can cache the content for up to 10 minutes (600 seconds).
We can change this behavior by adding these line to “firebase.json”, all value are calculated in milliseconds:
7776000 ms (90 days) for images, fonts, html, css, js files
604800 ms (7 days) for mp3 files
300 ms for our “404.html” file
"headers": [ { "source": "**/*.@(ttf|svg|woff|)", "headers": [ { "key": "Cache-Control", "value": "max-age=7776000" } ] }, { "source": "**/*.@(html|js|css)", "headers": [ { "key": "Cache-Control", "value": "max-age=7776000" } ] }, { "source": "**/*.@(jpg|jpeg|png)", "headers": [ { "key": "Cache-Control", "value": "max-age=7776000" } ] }, { "source": "**/*.@(mp3)", "headers": [ { "key": "Cache-Control", "value": "max-age=604800" } ] }, { "source": "404.html", "headers": [ { "key": "Cache-Control", "value": "max-age=300" } ] } ]
How to use Firebase hosting with GitHub CI/CD
You can integrate your Firebase hosting work flow easily with GitHub using GitHub actions.
Firebase will use GitHub actions to:
Creates a new preview channel for every PR (pull request) on your GitHub repository.
Adds a comment to the PR with the preview URL so that you and each reviewer can view and test the PR’s changes in a "preview" version of your app. And update the “preview" URL with each new commit.
Optionally deploys the current state of your GitHub repo to your live channel when the PR is merged.
Let’s try it
Create your GitHub repository (private or public).
In your project terminal, run these commands
git init
git add .
git commit -m "first commit"
This will initialize a git repository for our project, stag then commit all changes.
Then
git remote add origin https://_your_GitHub_repo_url
git branch -M main
git push -u origin main
With that we will rename our git branch to main, then push all files to the remote GitHub repo.
We are now ready to start using Firebase hosting with GitHub actions
Because we had ALREADY set up Hosting, we just need to set up the GitHub Action part of Hosting by running this command:
firebase init hosting:github
Then enter the name of your repo, In our case: adelpro/myproject
✔ Success! Logged into GitHub as adelpro
? For which GitHub repository would you like to set up a GitHub workflow? (format: user/repository)
Then
Set up the workflow to run a build script before every deploy?
answer: “N”
? Set up automatic deployment to your site's live channel when a PR is merged?
answer: “Y”
? What is the name of the GitHub branch associated with your site's live channel?
answer: main
With that we have successfully configured our GitHub actions
✔ Firebase initialization complete!
Now, whenever you push changes to the remote main branch, GitHub will automatically deploy this change to Firebase hosting using GitHub actions.
Let’s try it
make some changes
On your git main branch, run
git add .
git commit -m "new commit"
git push
Now go to GitHub.com actions section to see the automated deployment process.
Now our website is automatically deployed to Firebase hosting by GitHub actions.
How to deploy a React App using Firebase Hosting?
Guess what? It’s very easy to deploy React application using Firebase hosting, we will take the same approach in this article, with a minor modification.
We will modify these two lines in “firebase.json”
{
"hosting": {
"public": "build",
"predeploy": "npm run build",
...
}
}
We changed the default hosting folder to “/build” witch is the default folder for the create-react-app build command
We added a new entry :”predeploy” that will be automatically executed before starting the deployment process.
It’s all, your React application is ready to deployment.
firebase deploy
To deploy your React app with Firebase hosting using GitHub actions, you can add one line to our precedent process.
Open “firebase-hosting-pull-request.yml”, then just after this line
steps:
- uses: actions/checkout@v2
Add
steps:
- uses: actions/checkout@v2
- run: npm ci && npm run build
With that, before every deployment from GitHub, the build command will be automatically executed.
How to deploy a NextJS App using Firebase Hosting?
As you can see in the official Firebase Hosting documentation:
Using the Firebase CLI, you can deploy your Next.js Web apps to Firebase and serve them with Firebase Hosting. The CLI respects your Next.js settings and translates them to Firebase settings with zero or minimal extra configuration on your part. If your app includes dynamic server-side logic, the CLI deploys that logic to Cloud Functions for Firebase.
To deploy your NextJS to Firebase hosting, you can use the same logic with React deployment above, but if your NextJs app includes dynamic server-side logic, you have to use Firebase Cloud Functions, the first 2,000,000 invocations, 400,000 GB-sec, 200,000 CPU-sec, and 5 GB of Internet egress traffic is provided for free each month.
Conclusion
In this article, we have discussed how to deploy our website using Firebase Hosting for free, with different configurations and options.
We also discussed how to use Firebase Hosting advanced techniques like cache-controle and automatic deployment with GitHub actions.
Finally we talked about how to integrate Firebase hosting workflow with ReactJS and NextJS.
Thanks for reading