Automatically deploy a Gatsby site to Firebase Hosting

1,583
CircleCI
CircleCI’s continuous integration and delivery platform helps software teams rapidly release code with confidence by automating the build, test, and deploy process. CircleCI offers a modern software development platform that lets teams ramp quickly, scale easily, and build confidently every day.

This post was written by Kevin Ndung'u, a Web Developer from Nairobi, Kenya


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

Gatsby is a framework that enables you to 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 CMSs. It then combines this data with a React-based frontend architecture to build extremely fast interactive websites. Gatsby compiles web apps to optimised static files, which we will deploy to Firebase Hosting. I think it’s amazing and I’m glad to share it with you!

In this post, we will setup a simple Gatsby site, host the code on a GitHub repository, and setup automatic deployment of our web application to Firebase Hosting using CircleCI.

Prerequisites

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

  1. Git
  2. Node.js

Note: You’ll also need to have a Google account in order to use Firebase Hosting.

Why Gatsby?

I chose Gatsby simply because it will enable us to focus on the high level details. For example, rather than building pages from scratch, figuring out routing, adding 404 pages, and so on, we will get all these built in to the starter project that we will generate shortly. Gatsby affords us 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, we need to install Gatsby in our local development environment. We can do this by running:

npm install --global gatsby-cli

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

gatsby new gatsby-site

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

cd gatsby-site

And finally, we can explore our generated site by starting the development server:

gatsby develop

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. It looks like this:

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 we 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 us a functional web application that we can now deploy to Firebase Hosting.

Pushing to GitHub

At this point, let’s initialise a new Git repository and push the code to GitHub. Go ahead and initialise a new Git repository inside the gatsby-site folder and create an initial commit with these lines:

git init
git add -all
git commit -m "Generate Gatsby site"

After this, proceed to create a new repository on GitHub and push the code to the repository.

This guide is an excellent resource you can refer to if you’re not familiar with GitHub.

Firebase setup

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

  • Give your project a name in the modal that shows up and click Create project.

Once the project is created, we need to setup Firebase locally in order to link our local repository to the Firebase project. Install the Firebase command line tools by running:

npm install -g firebase-tools

We’ll also need to install the firebase-tools package locally to our 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 let’s install it right now:

npm install -D firebase-tools

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

firebase login

Once you are logged in, we can now initialise our project:

firebase init

This action will produce this prompt where we will select Hosting:

For the rest of the prompts, select the options as shown in the next screenshot:

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:

{
  "projects": {
    "default": "gatsby-site-43ac5"
  }
}

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

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

Manual deployment to Firebase

The first step in manual deployment is generating an optimised production build. In our case, gatsbyhas us covered since it includes this by default. To generate it, run the command:

gatsby build

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

firebase deploy

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

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

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

CircleCI configuration

To build our project with CircleCI, we’ll need to add a configuration file that instructs CircleCI to build our web application and automatically deploy it to Firebase each time we make changes to our code.

In our 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 we’ll use for our project:

# CircleCI Firebase Deployment Config
version: 2
jobs:
  build:
    docker:
      - image: circleci/node:10
    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"

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

  • First, the version key enables us to specify that we are using CircleCI 2.0.
  • Next up, we specify the base Docker image where our code will be run. In this case is a container based on Node 10, which is the current version at the time of writing this. You can use a later version if one is available.
  • The working_directory option specifies the location where our 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.
  • We then run the Gatsby Build command. This builds the optimized production version of the site, which is ready to be deployed.
  • Finally, we run the Firebase Deploy command that deploys our code to Firebase Hosting. In this step, you’ll notice that we need a Firebase token to allow deploying the app to our 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 we are running the firebase command from our locally installed dependencies rather than as a global command. As mentioned earlier, installing packages globally with CircleCI can be an issue, so we install all the packages we need locally in our project.

Integrating CircleCI and GitHub

We now have a config file and we can go ahead and integrate CircleCI with our GitHub repository that we created earlier.

  • Create an account on CircleCI, if you haven’t already.
  • Once you are logged in, ensure your account is selected on the top left corner.

  • Click Add Projects on the left sidebar.
  • On the next page, search for the name of your GitHub repository then click Set Up Project next to it.

  • On the next page, there’s a list of steps that are needed to build our project, the most important one being adding the CircleCI config file. Since we already have this file in our repo, let’s scroll all the way to the bottom and click Start Building.

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

Fortunately, I know why the deploy fails. It’s because we’ve 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, we will need to generate a Firebase token that we’ll use to allow access to our account. This token will enable CircleCI to deploy to Firebase on our behalf, since we cannot login using Firebase’s interactive prompt in a CI environment.

In our local development environment, let’s run this command to generate the token:

firebase login:ci

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.

Now that we have our token, all that’s left is to add the token as an environment variable in CircleCI so that we can use it in our project. Our deployment command expects to find the value in the FIREBASE_TOKENenvironment variable.

Adding the Firebase Token to CircleCI

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

  • Go to your project’s settings by clicking the gear icon next to your project.
  • Under the Build Settings section, click Environment Variables.
  • Click Add Variable.
  • In the modal that appears, enter FIREBASE_TOKEN in the name field, add the token we got from Firebase in the value field, then finally click Add Variable to finalize adding the variable.

  • With this step complete, we can now rerun our build by clicking Rerun Workflow on the right of the CircleCI project page.

We now have completed a successful deployment of our web application to Firebase Hosting using CircleCI! 🎉

Conclusion

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

This approach will work for any other frontend 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, see the following 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.

CircleCI
CircleCI’s continuous integration and delivery platform helps software teams rapidly release code with confidence by automating the build, test, and deploy process. CircleCI offers a modern software development platform that lets teams ramp quickly, scale easily, and build confidently every day.
Tools mentioned in article
Open jobs at CircleCI
Senior Full Stack Engineer - Core Team
North America, Ireland, Germany or the UK

At CircleCI, we enable thousands of developers to do better work every day. We're looking for full-stack folks to nurture the systems that make it possible.

The Core mission is to provide best-in-breed Continuous Integration and Continuous Delivery. As a Core member, you’ll own essential microservices and build features at the heart of our platform: Orbs, Pipelines, permissions, our data model, and the CLI, for example. You’ll also collaborate daily with talented colleagues across North America and western Europe.

This is a full-time role at the E3 level, and requires participation in our on-call support rotation.

What You’ll Do:

  • Design and build new features, simplify existing services, and scale our systems as we rapidly grow and evolve.
  • Write sustainable, testable, high-quality, high-performance code.
  • Support, maintain and debug microservices in a complex distributed system.
  • Foster a culture of observability and monitoring: use operational data to help your team increase the stability, performance, and usage of our systems.
  • Partner with members of a cross-functional team and other stakeholders to set the direction of our product: learn about our business problems, explore solutions, weigh design tradeoffs, write effective user stories, and prioritize them to deliver maximum value in a sustainable, incremental fashion.

What we're looking for:

  • 3+ years of full stack professional experience building and debugging distributed systems in production environments.
  • You write code that’s easily readable, testable, and maintainable, with an eye towards baking observability in from the start.
  • You enthusiastically approach everything from HTML/CSS to API design with the same level of respect and intention. You don’t need to be an expert in everything; T-shaped folks with an emphasis on frontend skills are ideal for these roles.
  • You’re interested in learning new languages and technologies. We use JavaScript/React, Go and Clojure, MongoDB and PostGreSQL, and RabbitMQ, but it’s okay if you haven’t yet. You can find more details on our tech stack here.
  • You’re good at navigating and shaping the dynamics of a rapidly-growing company with a remote-first culture: quickly adapting when priorities change and making conscious tradeoffs with incomplete information.

We’re Particularly Interested In People Who:

  • Work transparently and collaboratively within a distributed team.
  • Favor regular, incremental delivery over perfection.
  • Strive for continuous learning and improvement for themselves and their teams.
  • Are excited about ensuring that all of our systems—software and human—scale smoothly.

About CircleCI

CircleCI is the world’s largest shared continuous integration and continuous delivery (CI/CD) platform, and the central hub where code moves from idea to delivery. As one of the most-used DevOps tools that processes more than 1 million builds a day, CircleCI has unique access to data on how engineering teams work, and how their code runs. Companies like Spotify, Coinbase, Stitch Fix, and BuzzFeed use us to improve engineering team productivity, release better products, and get to market faster.

CircleCI is proud to be an Equal Opportunity and Affirmative Action employer. We do not discriminate based upon race, religion, color, national origin, sexual orientation, gender, gender identity, gender expression, transgender status, sexual stereotypes, age, status as a protected veteran, status as an individual with a disability, or other applicable legally protected characteristics. We also consider qualified applicants with criminal histories, consistent with applicable federal, state and local law.

Staff Software Engineer - Growth Acti...
North America

Come help us build the world’s most reliable and fastest-growing CI/CD system! Our customers range from well-known household brands to small startups and everywhere in between. We’re growing at a high pace and we need you to help us scale further.

CircleCI is looking for a Staff Full Stack Software Engineer to help us lead Activation Team engineers through technical mentorship and strategy across the frontend and backend stacks. You will join a team of full-stack engineers that are empathetic and curious about the experience of our new users. As we expand our growth teams, we are looking for someone who can help us become more effective. You’ll be able to expand your skills by exploring the ways in which engineering can directly contribute to the growth of our business.

This is a full-time role at the E4 level on our Engineering Competency Matrix, and requires participation in our on-call support rotation.

Our Team

The Activation Team, along with our business partners, have made it our mission to help CircleCI’s newest users succeed with CI/CD. To that end we are optimizing the onboarding experience of our new users, by guiding them as they learn our tool, educating more advanced features and by helping them prevent and correct errors.

We achieve this by implementing and optimizing features with a data-driven approach. We conduct experiments in four phases: ideation, hypothesis, design and analysis. Based on the result, we either further refine our experiment, or even roll it back and leave it behind. As long as we have learned something about our users, experiments are considered successful.

Our position within the engineering organization is unique: we frequently work with many teams across the CircleCI Platform and are positioned to influence the future direction of the product.

What you’ll get to do:

  • Lead and unblock the engineers on your team.
  • Identify and resolve technical risk in future engineering work.
  • Facilitate communication with different engineering and business teams.
  • Collaborate with other growth teams to conceptualize and implement technical enablement strategies.
  • Support engineers in interpreting the results of experiments.
  • Guide the future of product at CircleCI:
  • Build the technical roadmap to scale successful experiments into full features.
  • Use learnings from unsuccessful experiments to guide the design of future work.
  • Use Clojure and a modern React.js frontend (if you don’t know them it’s okay!). You can find our entire tech stack here.

What we’re looking for:

We’re looking for someone who has a learning mindset, is curious and highly motivated to learn something new every day. They should also like to have impact on high visibility work for their business and be someone with an audience-driven communication style. If this sounds like you, here’s the additional experience we’re looking for:

  • Someone who can work across many engineering domains and is comfortable learning unfamiliar technology. You know how to guide a team to make decisions in an ambiguous environment, manage risk, and recover from mistakes.
  • A value-driven engineer who understands the tradeoffs between user, technical and business needs.
  • Someone who provides technical leadership, influencing the team’s technical output, strategy and standards.
  • You have a track record of mentoring and coaching developers on their team.
  • You’re curious about your users and always looking for ways to improve their journey through your product.
  • Someone that favors regular, incremental delivery over perfection while incorporating regular feedback from users and stakeholders.
  • Experience working with distributed systems such as microservice architectures.
  • Someone comfortable with being on a pager rotation.

We’re Particularly Interested In People Who Are:

  • Mindful of developer happiness.
  • Experienced in working in a distributed environment.
  • Previously experience in a growth engineering, data pipeline team, or innovation team.

Work remotely with our globally distributed team!

We’re a distributed company with teammates across the world. Our Growth teams are distributed across North America. For this role, we are hiring engineers to work remotely in the United States and through our affiliate, Continuous Labs, in the following Canadian provinces: Alberta, British Columbia, Manitoba, New Brunswick, Newfoundland and Labrador, Nova Scotia, Ontario, Prince Edward Island and Saskatchewan.

About CircleCI

CircleCI is the world’s largest shared continuous integration and continuous delivery (CI/CD) platform, and the central hub where code moves from idea to delivery. As one of the most-used DevOps tools that processes more than 1 million builds a day, CircleCI has unique access to data on how engineering teams work, and how their code runs. Companies like Spotify, Coinbase, Stitch Fix, and BuzzFeed use us to improve engineering team productivity, release better products, and get to market faster.

CircleCI is proud to be an Equal Opportunity and Affirmative Action employer. We do not discriminate based upon race, religion, color, national origin, sexual orientation, gender, gender identity, gender expression, transgender status, sexual stereotypes, age, status as a protected veteran, status as an individual with a disability, or other applicable legally protected characteristics. We also consider qualified applicants with criminal histories, consistent with applicable federal, state and local law.

Senior Site Reliability Engineer
North America

CircleCI is seeking a Senior Site Reliability Engineer to work closely with our Software Engineers to deliver and manage the high-performance and scalable infrastructure underlying our multi-tenant Cloud offering. You will not only have the chance to automate and optimize infrastructure through the construction of appropriate tooling, but you will help software engineers through the design phase to optimize their services for scale in our production /environment.

You'll join a highly distributed team building features and services designed specifically for macOS and iOS developers. You'll write sustainable, resilient code as part of an engineering organization that values collaboration, trust, and learning. You’ll be part of a team at the heart of CircleCI’s business responsible for build environments used by thousands of development teams every day.

About this role:

  • Design and deliver solutions to improve the availability, scalability, latency, and efficiency of CircleCI’s services
  • Foster a culture of observability and monitoring; helping your team use operational data to improve the stability and performance of our systems
  • Diagnose and resolve production issues in conjunction with software engineering teams -Implement shared infrastructure used by all services and teams within the CircleCI platform
  • Support and advise software engineering teams in the design of scalable services
  • Build and maintain tools for deployment, monitoring, and debugging
  • Execute disaster recovery drills
  • Participate in rotating on-call duties, including incident management

About you:

  • Proficiency in one or more of: Go, Java, Python, C or C++, Clojure
  • Experience working with Docker, Kubernetes, Terraform, Helm, AWS, and modern distributed SaaS infrastructure.
  • Knowledge of virtualization technologies, such as VMware or KVM
  • Understanding of standard networking protocols and components such as: TCP/IP, HTTP, DNS, ICMP, VLANs, the OSI Model, IP Subnetting, and Load Balancing
  • Knowledge of operating systems (processes, threads, IPC, concurrency, locks, mutexes, semaphores, etc.)
  • Understanding of good monitoring and alerting practices, using tools like Datadog and Pagerduty
  • Knowledge of the internal workings of at least one of: PostgreSQL, MongoDB, Redis
  • Focus on security in the delivery of all levels of a system
  • Passion for modern software development and operation, including agile, CI/CD, and infrastructure-as-code
  • Desire to learn and grow career as a Site Reliability Engineer
  • 2 or more years of experience

We know there’s no such thing as a “perfect” candidate - we’re all a work in progress and are growing new skills and capabilities all the time. CircleCI welcomes those who are enthusiastic about learning and evolving, so however you identify and whatever your background, if this looks like a role where you could do work that excites you, we hope you’ll apply.

Work remotely with our globally distributed team!

We’re a distributed company with teammates across the world. For this role, we are hiring engineers to work remotely in the United States and through our affiliate, Continuous Labs, in the following Canadian provinces: Alberta, British Columbia, Manitoba, New Brunswick, Newfoundland and Labrador, Nova Scotia, Ontario, Prince Edward Island and Saskatchewan.

About CircleCI

CircleCI is the world’s largest shared continuous integration and continuous delivery (CI/CD) platform, and the central hub where code moves from idea to delivery. As one of the most-used DevOps tools that processes more than 1 million builds a day, CircleCI has unique access to data on how engineering teams work, and how their code runs. Companies like Spotify, Coinbase, Stitch Fix, and BuzzFeed use us to improve engineering team productivity, release better products, and get to market faster.

CircleCI is proud to be an Equal Opportunity and Affirmative Action employer. We do not discriminate based upon race, religion, color, national origin, sexual orientation, gender, gender identity, gender expression, transgender status, sexual stereotypes, age, status as a protected veteran, status as an individual with a disability, or other applicable legally protected characteristics. We also consider qualified applicants with criminal histories, consistent with applicable federal, state and local law.

Senior UX/Frontend Engineer
(United States or Canada)

At CircleCI, we enable thousands of developers to do better work every day. Providing best-in-breed Continuous Integration and Continuous Delivery is our mission, and we’re looking for experienced UX/frontend engineers to help with that.

As a member of our Design System team, you’ll build beautiful, accessible, reusable UI components that define our user experience. You’ll also collaborate daily with dedicated colleagues across North America and western Europe.

This is a full-time role at the Senior Engineer level.

What You’ll Do:

  • Collaborate with product designers, engineering teams, and other stakeholders to help design and implement new features, simplify the existing codebase, and scale our systems as we rapidly grow and evolve.
  • Curate the frontend component library in a complex distributed system.
  • Continuously improve our user experience.
  • Create documentation and guidelines for different consumers — including internal backend and frontend engineers, project managers, external clients, and CircleCI’s users.
  • Help set the direction of our product: learn about our business problems, explore solutions, weigh design tradeoffs, write effective user stories, and prioritize them to deliver maximum value in a sustainable, incremental fashion.

What we're looking for:

  • 3+ years of professional experience building reusable frontend components that can be applied across platforms (macOS, Linux, Windows).
  • Engineers with strong component and design systems knowledge. You’re not a designer, but you have an eye for typography, layout systems, and colour, plus the ability to implement these systems with JS frameworks and type systems (we use React and TypeScript, but it’s fine if you haven’t yet).
  • Deep understanding of semantic HTML and client-side JavaScript.
  • An appreciation for writing unit and end to end tests.

We’re Particularly Interested In People Who:

  • Work transparently and collaboratively within a distributed team.
  • Favor regular, incremental delivery over perfection.
  • Strive for continuous learning and improvement for themselves and their teams.
  • Are excited about ensuring that all of our systems—software and human—scale smoothly.

About CircleCI

CircleCI is the world’s largest shared continuous integration and continuous delivery (CI/CD) platform, and the central hub where code moves from idea to delivery. As one of the most-used DevOps tools that processes more than 1 million builds a day, CircleCI has unique access to data on how engineering teams work, and how their code runs. Companies like Spotify, Coinbase, Stitch Fix, and BuzzFeed use us to improve engineering team productivity, release better products, and get to market faster.

CircleCI is proud to be an Equal Opportunity and Affirmative Action employer. We do not discriminate based upon race, religion, color, national origin, sexual orientation, gender, gender identity, gender expression, transgender status, sexual stereotypes, age, status as a protected veteran, status as an

Verified by
Sr. Solutions Engineer
Head of DevRel & Community
Vice President of Marketing
Software Engineer
Support Engineer
Developer Evangelist
Technical Content Marketing Manager
You may also like