No results for

TutorialsJun 18, 201911 min read

Automatically deploy a Gatsby site to Firebase Hosting

Kevin Ndung'u

Software Engineer

Developer A sits at a desk working on an intermediate-level project.

Note from the publisher: You have managed to find some of our old content and it may be outdated and/or incorrect. Try searching in our docs or on the blog for current information.


Firebase Hosting is a web application hosting platform by Google. Using this service, you can host your web apps on Google’s infrastructure. It enables easy one-step deployment and has other cool features like fast hosting from CDNs and rollbacks. A good overview of the service is available in the Firebase Hosting Docs.

Gatsby is a framework that helps you create fast React-based apps and websites. It allows you to build these websites with data fetched from a wide variety of sources, including markdown files, APIs, and even content management systems. It then combines this data with a React-based frontend architecture to build extremely fast interactive websites. Gatsby compiles web apps to optimized static files, which you deploy to Firebase Hosting. I think it’s amazing and I’m glad to share it with you.

In this tutorial, you will setup a simple Gatsby site, host the code on a GitHub repository, and set up automatic deployment of your web application to Firebase Hosting using CircleCI.

Prerequisites

To go through this tutorial, you will need to install the following:

Why Gatsby?

I chose Gatsby for this tutorial because it will enable you to focus on the high level details. For example, rather than building pages from scratch, figuring out routing, adding 404 pages, and so on, you will get all these built in to the starter project. Gatsby affords you these advantages out of the box, but the concepts of hosting will still apply to any other type of web application that can be compiled to static files including Vue and Angular apps or even a website generated by a static site generator.

Gatsby project setup

First, you need to install Gatsby in your local development environment. You can do this by running:

npm install --global gatsby-cli
Copy to clipboard

After the installation is complete, you will have the gatsby command available. Now, use the Gatsby CLI to generate a new site:

gatsby new gatsby-site
Copy to clipboard

Next, you need to change directories to the newly created gatsby-site folder:

cd gatsby-site
Copy to clipboard

And finally, you can explore your generated site by starting the development server:

gatsby develop
Copy to clipboard

Your new site is now accessible on http://localhost:8000/.

If everything ran successfully, you now have a Gatsby site running locally. Go ahead and explore the site.

Local project

If you take a look around through the generated files, you’ll find that Gatsby’s folder structure is simple to follow. For example, the code for the homepage can be found in src/pages/index.js. Also notice that links between different pages work as expected and you also have a 404 page set up. You can test the 404 page by going to a non-existent route.

Gatsby provides these low level details, such as routing, out of the box and gives you a functional web application that you can now deploy to Firebase Hosting.

Pushing to GitHub

At this point, you have a new Git repository automatically initialized by gatsby CLI. Remember that installing Git is a prerequisite.

Now, push the code to GitHub (This linked blog post is an excellent resource you can refer to if you’re not familiar with GitHub).

Firebase setup

Firebase project setup

At this point, you have a functional website that you can now deploy to Firebase Hosting. Before you do this, you need to create a new project on Firebase using these three simple steps:

  1. Go to https://firebase.google.com and sign in with your Google account.
  2. Click Go To Console at the top-right side of the nav bar or access the console through https://console.firebase.google.com.
  3. Click Create a project (or Get started with a Firebase project if this is your first).

Create Firebase project

Give your project a name in the modal that shows up and click Continue. Unselect Google Analytics for now then click Create project.

Note: Selecting Google Analytics, requires that you choose or create a Google Analytics which is not in the scope of this tutorial.

Click Continue, once the spinner loads, and the project is created.

Create Firebase project

Firebase CLI setup

Next, you need to setup Firebase locally in order to link your local repository to the newly-created Firebase project. Install the Firebase command line tools (Firebase CLI) by running:

npm install -g firebase-tools
Copy to clipboard

We’ll also need to install the firebase-tools package locally to your project as a devDependency. This will come in handy later on when integrating with CircleCI, which does not allow installing packages globally by default. So install it right now:

npm install -D firebase-tools
Copy to clipboard

Afterwards, you need to sign in to Firebase to connect the Firebase CLI to the online Firebase account. You can do this by running:

firebase login
Copy to clipboard

Once you are logged in, you can initialise your project:

firebase init
Copy to clipboard

This action will produce a prompt where you will select Hosting (under Firebase features).

For the next prompt (Project Setup), select Use an existing project option, since you already created a Firebase project in the previous step. Then select the name of the new project you created.

Make default selections for the rest of the prompts. As at the time of this writing, this was the output:

$ firebase init

     ######## #### ########  ######## ########     ###     ######  ########
     ##        ##  ##     ## ##       ##     ##  ##   ##  ##       ##
     ######    ##  ########  ######   ########  #########  ######  ######
     ##        ##  ##    ##  ##       ##     ## ##     ##       ## ##
     ##       #### ##     ## ######## ########  ##     ##  ######  ########

You're about to initialize a Firebase project in this directory:

  .../gatsby-site

? Which Firebase features do you want to set up for this directory? Press Space to select features, then Enter to confirm your choices.
Hosting: Configure files for Firebase Hosting and (optionally) set up GitHub Action deploys

=== Project Setup

First, associate this project directory with a Firebase project.
You can create multiple project aliases by running firebase use --add,
but for now you'll just set up a default project.

? Please select an option: Use an existing project
? Select a default Firebase project for this directory: cci-gatsby-site (cci-gatsby-site)
i  Using project cci-gatsby-site (cci-gatsby-site)

=== Hosting Setup

Your public directory is the folder (relative to your project directory) that
will contain Hosting assets to be uploaded with firebase deploy. If you
have a build process for your assets, use your build's output directory.

? What do you want to use as your public directory? public
? Configure as a single-page app (rewrite all urls to /index.html)? No
? Set up automatic builds and deploys with GitHub? No
✔  Wrote public/404.html
✔  Wrote public/index.html

i  Writing configuration info to firebase.json...
i  Writing project information to .firebaserc...

✔  Firebase initialization complete!
Copy to clipboard

After the prompts are complete, the Firebase CLI generates two files:

  • .firebaserc
  • firebase.json

Note: The firebase.json file enables configuring custom hosting behavior. To learn more about this, visit the Firebase full-config docs.

In the case that the Firebase CLI does not load your projects, you can add the project ID manually in the generated .firebaserc file. (Replace <your-firebase-project-name> with your project ID):

{
  "projects": {
    "default": "<your-firebase-project-name>"
  }
}
Copy to clipboard

This is also a good point to commit the new files to your repository and push the updated code to GitHub.

With this, you have connected your code to your Firebase project and you can now try out a manual deploy from your development environment.

Manual deployment to Firebase

The first step in manual deployment is generating an optimised production build. Helpfully, gatsby includes this by default. To generate it, run the command:

This generates an optimised static site in the public directory. This is the directory you will be deploying to Firebase Hosting. To manually deploy the public directory to Firebase Hosting, it only takes one command:

firebase deploy
Copy to clipboard

If everything works as expected, Firebase will deploy your site and give you a link to the deployed site’s URL.

Deployed project

You’ll also notice a new .firebase folder created by Firebase to store its cache. Since you don’t want this folder in your repository, you can add the folder name to the .gitignore file so it is ignored by Git.

In the next step, you are going to automate the deployment with CircleCI so that you can deploy new changes pushed to the repository immediately.

CircleCI configuration

To enable CI/CD, let’s build your project with CircleCI, you’ll need to add a configuration file that instructs CircleCI to build your web application and automatically deploy it to Firebase each time you make changes to your code.

In your project’s root folder, create a folder named .circleci and inside it, create a config.yml file. CircleCI requires that the config file be located here.

Here’s the config file you’ll use for your project:

# CircleCI Firebase Deployment Config
version: 2
jobs:
  build:
    docker:
      - image: cimg/node:lts
    working_directory: ~/gatsby-site
    steps:
      - checkout
      - restore_cache:
          keys:
            # Find a cache corresponding to this specific package-lock.json
            - v1-npm-deps-{{ checksum "package-lock.json" }}
            # Fallback cache to be used
            - v1-npm-deps-
      - run:
          name: Install Dependencies
          command: npm install
      - save_cache:
          key: v1-npm-deps-{{ checksum "package-lock.json" }}
          paths:
            - ./node_modules
      - run:
          name: Gatsby Build
          command: npm run build
      - run:
          name: Firebase Deploy
          command: ./node_modules/.bin/firebase deploy --token "$FIREBASE_TOKEN"
Copy to clipboard

Let’s do a quick review of the config file.

  • First, the version key enables you to specify that you are using CircleCI 2.0.
  • Next up, specify the base Docker image where your code will be run. In this case is a container based on cimg:node/lts, which is the Long Term Support version. Refer to this reference. You can use another version if you prefer.
  • The working_directory option specifies the location where your code will be cloned.
  • Next is the restore_cache section, which instructs CircleCI to restore any previously installed dependencies. Here we’re using a checksum of the package-lock.json file to detect whether to install the dependencies afresh or to use the cache to restore previously downloaded packages.
  • The next step is installing the dependencies through the npm install command.
  • The save_cache section instructs CircleCI to save the dependencies after installing them.
  • Then run the Gatsby Build command. This builds the optimised production version of the site, which is ready to be deployed.
  • Finally, run the Firebase Deploy command that deploys your code to Firebase Hosting.

In the last step, you’ll notice that you need a Firebase token to allow deploying the app to your account. The command specifies that the token should be obtained from the FIREBASE_TOKEN environment variable. We’ll get this token in a moment.

Additionally, note the change in how you are running the firebase command from your locally installed dependencies rather than as a global command. As mentioned earlier, installing packages globally with CircleCI can be an issue, so you install all the packages you need locally in your project.

Commit these changes and push the code to GitHub.

Integrating CircleCI and GitHub

You now have a config file and you can go ahead and integrate CircleCI with your GitHub repository that you created earlier.

  1. Log in to CircleCI. Remember, having a CircleCI account was mentioned as a prerequisite.
  2. Once you are logged in, ensure your account is selected on the top left corner.
  3. Click Projects on the left sidebar.
  4. On the next page, search for the name of your GitHub repository then click Set Up Project next to it.

CircleCI project

  1. On the modal that opens, enter the Git branch name that contains the CircleCI config file. Once acknowledged by the text .circleci/config.yml found on this branch you can click Start Building.

Start building

Your build will finally start running, but it predictably fails in the Firebase deployment step.

Failed build

Fortunately, it’s clear why the deploy fails. You have not yet added the Firebase deploy token to CircleCI. Let’s work on fixing this in the next section.

Getting a Firebase login token to use for deployments

In the final step, you will need to generate a Firebase token to allow access to your account. This token will enable CircleCI to deploy to Firebase on your behalf, since you cannot login using Firebase’s interactive prompt in a CI environment.

In your local development environment, run this command to generate the token:

firebase login:ci
Copy to clipboard

This will open up a browser window where you’ll be prompted to login to your Firebase account. Once you’re signed in, a token will be generated. You should get a result similar to the following after authenticating via the web browser.

...
Waiting for authentication...

✔  Success! Use this token to login on a CI server:

<... Token ...>

Example: firebase deploy --token "$FIREBASE_TOKEN"
Copy to clipboard

Now that you have your token, all that’s left is to add the token as an environment variable in CircleCI so that you can use it in your project. Your deployment command expects to find the value in the FIREBASE_TOKEN environment variable.

Adding the Firebase Token to CircleCI

These are the steps you’ll need to take to add the token:

  1. Go to your project’s settings by clicking the button Project Settings (which has a gear icon preceding the words).
  2. Click Environment Variables on the left menu.
  3. Click Add Environment Variable.
  4. In the modal that appears, enter FIREBASE_TOKEN in the name field, add the token you got from Firebase in the value field, then finally click Add Environment Variable to complete.
  5. With this step complete, you can now rerun your build by clicking the back button (at the top left).

Adding environment variables

Click Rerun Workflow from failed (or the icon left to it “Rerun Workflow from start”) on the right of the CircleCI project build card.

Rerun CircleCI

You now have completed a successful deployment of your web application to Firebase Hosting using CircleCI!

Build successful

Conclusion

This concludes your exploration of deploying web applications to Firebase using CircleCI. From now on, when you make updates to your Gatsby site and push the changes to GitHub, they will automatically be deployed to Firebase Hosting through your CI/CD pipeline. It really is a great combination.

This approach will work for any other front-end projects and is not specific to Gatsby. Firebase provides the hosting for the web applications and CircleCI helps in automating and simplifying the process. Go forth and deploy!

For more information on these technologies, review these resources:


Kevin Ndung’u is a software developer and open source enthusiast currently working as a software engineer at Andela. He is passionate about sharing his knowledge through blog posts and open source code. When not building web applications, you can find him watching a game of soccer.

Copy to clipboard