Automatically deploy a Gatsby site to Firebase Hosting

2,068
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
Backend Engineering Manager
Anywhere from UTC-8 to UTC+1
CircleCI is looking for a technology leader who brings exceptional management and technical skills to our growing team of back end developers. The back end team is currently building out our microservices infrastructure, and we are looking for a leader well versed in distributed systems and functional programming to guide the team as we scale.  In this role you will challenge and grow our engineers with the individual in mind. Your primary focus is your team and the people in it, and we expect you to build a great culture with diversity as a core value. We are proud to foster a workplace free from discrimination. We strongly believe that diversity of experience, perspectives, and background will lead to a better environment for our employees and a better product for our users. 
  • Develop people through coaching, mentoring, and management support
  • Work with other development teams, Product Owners, and others to maintain high levels of transparency, efficiency, and collaboration
  • Advocate and promote leadership at all levels within the CircleCI engineering community
  • Grow the technical expertise of your teams in performance, scalability, maintainable architecture and experimentation
  • Participate in architecture discussions guiding our use of Clojure, microservices and other distributed technologies
  • Work with the recruiting team to attract, onboard, and retain diverse top talent
  • You thrive when developing great people, not just great products
  • You are knowledgeable and passionate about software engineering practices, primarily focused on distributed systems technologies
  • You have at least three years of experience leading, coaching and mentoring software development teams and delivering working software together with them
  • You know what it takes to build a team, you believe in agile & lean values and you are a servant leader
  • You bring energy, positivity and drive to the teams you work with
  • Customer Success Engineer - Japan
    Tokyo, Japan
    As a Customer Success Engineer, you will be responsible for providing world class post-sales technical leadership to our client base. Working directly with customers you will be the subject matter expert on continuous integration and deployment as a practice and CircleCI. You will be responsible for delivering value by driving adoption of our platform across the client’s enterprise. Finally, you will have the opportunity to work directly with our Product Management, Engineering, Customer Success, and Marketing teams to share your knowledge and experiences to ultimately improve our customers’ success with CircleCI. You will be the main point of contact for all technical questions and assistance for these customers and represent their needs back to customer success, product management, engineering, and marketing.  And, you will work with the rest of the Customer Success team to build out and cultivate a customer community to enhance the experience of our customers. The successful candidate for this job will have a strong technical aptitude along with a strong self-starting, proactive mentality as well as the ability to create and maintain deep, lasting relationships with customers.  You’re going to be dealing with very technical users and complex issues, but you’re also tasked with creating excitement and loyalty in the customers you interact with. About CircleCI CircleCI provides software development teams the confidence to build, test, and deploy—quickly and consistently—across numerous platforms. Built to address the demanding needs for today's application development environments, CircleCI supports all types of software testing including web, mobile and container (Docker) environments. CircleCI makes continuous integration and continuous deployment simple and easy for thousands of companies like Shopify, Cisco, Sony and Trunk Club, so they can ship better code, faster. CircleCI is venture backed by Draper Fisher Jurvetson, Baseline Ventures, Harrison Metal Capital, Data Collective, 500 Startups, SV Angel, and a collection of respected angels. About Customer Engineering at CircleCI CircleCI’s Customer Engineering Team’s goal is to make life easier for our customers and leave them with the “wow” experience of building and testing their applications with ease. The Customer Engineering Team works with customers to understand their technical and business needs and requirements - from onboarding to implementation to scale. The Customer Success Engineer works with and across the Engineering, Product, and Revenue teams at CircleCI to drive platform adoption and help customers solve their technical challenges.
  • Work closely with customers to help with setting up their CircleCI account and building any custom setup to help customers get the most out of CircleCI
  • Partner with your Customer Success Manager to onboard and support our customers as well as act as the dedicated technical point of contact
  • Be creative and scrappy in solving customer technical problems and answering customer questions
  • Build best practices for onboarding across different technologies
  • Act as the voice of the customer and use customer feedback to help Product and Engineering improve the product
  • Code and commit relevant upgrades and changes to the CircleCI codebase
  • Work closely with the Product and Engineering teams to improve the customer experience across the whole platform
  • Become an expert on the CircleCI solution
  • 2+ years of technical product support, engineering, or experience deploying software in the enterprise
  • Work with customers directly to debug common errors without involving an engineer
  • You can tie business problems to technical solutions and understand technology value propositions
  • Demonstrated and proven capacity to quickly absorb new concepts and technologies
  • You have spent a decent amount of time using and scripting *nix
  • You know how to work with Git in general and ideally GitHub in particular
  • You’ve thrown together an app or two in a high-level programming language
  • You believe that the best way for all to succeed is to honestly discuss product and company abilities and limitations with customers. We do not oversell at CircleCI
  • Strong ops / infrastructure knowledge, especially networking and security
  • Great relationship building skills and a good people person
  • Fluency in Japanese; exceptional written and oral communication skills
  • Experience with build, test, and deployment automation, either as a practitioner or in a customer-facing role
  • Ability to troubleshoot networking issues that may prevent communication between different components
  • Knowledge of Docker or Linux containers in general
  • Experience with popular web app frameworks (e.g. Rails, Django) and/or mobile app development (iOS, Android)
  • Experience using and automating a major IaaS like AWS, GCP, or Azure
  • Familiarity deploying and debugging distributed systems
  • Developer Advocate - Content Producer
    San Francisco, California
    Our mission is to help people everywhere build and deliver software at the speed of imagination. As a Developer Advocate - Content Producer at CircleCI, you will have extensive influence over our voice, content, community building, and ecosystem. The ideal candidate is a passionate CircleCI user who loves writing about development practices, helping others, and sharing what they know, but could also be an experienced copywriter with a strong technical background. This person should be reasonably familiar and fluent in technologies like: Docker, AWS, CI/CD, DevOps, Kubernetes, Linux, application development, etc. As a content producer, you will work in the marketing team, and be responsible for creating and overseeing the production and quality of technical content for our blog and other properties. You will own the growth of our brand-new guest writer community of freelancers for the CircleCI blog, creating systems to help it grow and thrive, including research, topic generation, community building, and quality control. You will be writing and editing blog posts, including testing code snippets. You will also be relied upon for writing marketing copy for landing pages and more, maintaining brand guidelines and writing for multiple audiences. There is tons of room in this role for producing more creative projects including tutorials, narrative content, and video -- the sky’s the limit! We value unique voices, and look to create human, useful content. You can get a feel for our team and our brand voice in some of our favorite pieces here: https://circleci.com/blog/a-brief-history-of-devops-part-i-waterfall/ https://circleci.com/blog/interviewing-as-an-outsider-how-i-finally-got-seen-in-tech/ https://circleci.com/blog/testing-docker-images-with-circleci-and-goss/ This is a contract position while a team member is on family leave. We would like this person to start as soon as possible, and work full-time until mid-January. About CircleCI CircleCI is the best platform for software teams looking to rapidly build quality projects, at scale. Our intelligent continuous integration and delivery tools are simple yet powerful. Our aim is to provide the wisdom of a connected development ecosystem to every team member making technology decisions. We run 12M+ builds a month on our platform for companies like Spotify, Kickstarter, Sony, and Coinbase. Over 25,000 organizations and 300,000 developers actively build, test, and deploy on CircleCI.  We’ve raised $59.5M in venture capital from Industry Ventures, Top Tier Capital, Scale Venture Partners, DFJ, Harrison Metal Capital, and Baseline Ventures.
  • Write and edit technical content for the CircleCI blog, including tutorials and code snippets.
  • Manage CircleCI’s Guest Writer Program: including expanding our pool of freelancers, owning the direction of content, and managing the day-to-day of the program
  • Be a point-person for technical questions related to written content
  • Copywriting for a technical audience, including: landing pages, email, conference booths, ads, and other marketing needs as they arise.
  • Ensure communications are technically correct and tonally appropriate for our audience
  • Create new content streams: research papers, videos, interactive tutorials or guides, etc.
  • You have proven success as a writer for a technical audience.
  • You have experience in marketing or community management.
  • You have a deep understanding of CI/CD and DevOps more generally.
  • You should be familiar with our product and be able to articulate _why_ CircleCI can help engineering teams be more productive, happier, and successful.
  • You are self-directed and strategic: the ideal candidate will be able to set a course, articulate why that course will deliver the highest value and impact to the company, and execute on that direction.
  • You enjoy writing and content creation in general (bonus if you have YouTube experience).
  • You deeply enjoy sharing what you know and helping others to grow.
  • Strong grasp of English writing, grammar and mechanics and feel comfortable editing.
  • Share 3-5 writing samples. A mix of technical and non-technical writing is fine. Write a short cover letter, and tell us why you're passionate about DevOps and CircleCI.
  • Developer Community Manager - Japan
    Tokyo, Japan
    Our mission is to help people everywhere build and deliver software at the speed of imagination. As a developer advocate at CircleCI, you will have extensive influence over our voice, content, community building, and ecosystem. This is a position for engineers who love connecting with developers and speaking publicly about developer productivity and team success on conference panels, at user groups, on blogs, in docs, and internally. Your work grows and sustains the large community of developers in Japan who rely on CircleCI as a fundamental part of their daily work. As our first community manager and developer advocate in Japan, you will be responsible for creating our programs from the ground up. You will own both the strategy and execution for reaching and growing our audience in Japan. The ideal candidate is a passionate CircleCI user who deeply understands our product, and also has an affinity for community management and marketing. About CircleCI CircleCI is the best platform for software teams looking to rapidly build quality projects, at scale. Our intelligent continuous integration and delivery tools are simple yet powerful. Our aim is to provide the wisdom of a connected development ecosystem to every team member making technology decisions. We run 7M+ builds a month on our platform for companies like Spotify, Kickstarter, Sony, and Coinbase. Over 25,000 organizations and 300,000 developers actively build, test, and deploy on CircleCI.  We’ve raised $59.5M in venture capital from Industry Ventures, Top Tier Capital, Scale Venture Partners, DFJ, Harrison Metal Capital, and Baseline Ventures.
  • Define and execute the marketing and evangelism plan to reach developers in Japan, including managing budget and regular reporting
  • Speak at conferences on behalf of CircleCI, organize meetups, and host events
  • Create and run our user groups in Japan
  • Monitor and respond to technical questions in Japanese on Twitter, Stack Overflow, Quora, our Discuss community, and elsewhere
  • Create Japanese content that speaks to our audience of developers: conference talks, blog posts, videos, and more
  • Advocate with product, marketing, engineering, and revenue teams for changes we can make on behalf of our customers -- report on issues our customers are having, what other players in the space are doing, and where we can make improvements
  • Be the main point of contact, editor, and translator for the marketing and localization team to help make sure communications are technically correct and tonally appropriate for our audience
  • You have built, run, and scaled user groups in Japan for a tech company in the past.
  • You have previous experience as a developer advocate and/or community manager
  • You have a deep understanding of CI/CD and DevOps more generally.
  • You should be familiar with our product and be able to articulate _why_ CircleCI can help engineering teams be more productive, happier, and successful
  • You are self-directed and strategic: the ideal candidate will be able to set a course, articulate why that course will deliver the highest value and impact to the company, and execute on that direction
  • You enjoy networking, hosting events,  and speaking -- we’re looking for someone who is energized by meeting new people
  • You have native-level Japanese fluency and full professional proficiency in English, both written and oral
  • Verified by
    Head of DevRel & Community
    Vice President of Marketing
    Support Engineer
    Developer Evangelist
    Technical Content Marketing Manager
    You may also like