Learn Gatsby · 12/12

Production Deployment and CI/CD

8 min read

Production Deployment and CI/CD 🚀

Welcome to the final stage of your Gatsby journey! You've built a blazing-fast site on your local machine, and now it's time to share it with the world. This guide will walk you through transforming your local project into a live, production-ready website that automatically updates. Let's get this rocket into orbit!

1. Running Production Builds and Local Testing

The What and Why

Right now, you're likely running your site with gatsby develop. This command is fantastic for development because it's fast, shows changes instantly, and provides helpful debugging tools. However, it's not optimized for performance. It's like a chef taste-testing ingredients as they cook—great for the process, but you wouldn't serve those little experiments to a customer.

A production build is the process of compiling and optimizing your site's files (HTML, CSS, JavaScript) into a final version that is small, fast, and ready for your users. This process includes:

  • Bundling: Grouping your code into efficient packages.
  • Minification: Removing unnecessary characters (like spaces and comments) from your code to reduce file size.
  • Code Splitting: Breaking your code into smaller chunks that are loaded only when needed.
  • Generating Static Assets: Creating the actual HTML, CSS, and JavaScript files that will be served to your users.

Think of it as taking all the raw ingredients and a recipe from the test kitchen (develop) and creating a perfectly packaged, ready-to-eat meal (build) for your customers.

How to Do It: The "Build and Serve" Dance

Getting your site ready for production involves two simple commands from the Gatsby CLI.

Step 1: Create a Production Build 🏗️

To start the optimization process, run the following command in your project's root directory:

bash
gatsby build

You'll see a series of steps in your terminal as Gatsby works its magic. When it's finished, you'll find a new folder in your project called public. This folder contains your complete, production-ready website. This is the only folder you need to deploy.

Fun Fact: The gatsby build command is a "headless" process, meaning it doesn't need a browser to run. It's all happening behind the scenes in a Node.js environment.

Step 2: Test Your Production Build Locally 🕵️

Before you deploy, you absolutely must test the production version to make sure everything works as expected. Sometimes, things that work in development break in the production build.

To do this, Gatsby provides another command:

bash
gatsby serve

This command starts a local server to preview the contents of your public folder. You can then open your browser to http://localhost:9000 to see the final version of your site. Click around, test your links, and make sure everything is perfect.

This is your final quality check before launching. It's like the final inspection of a car before it leaves the factory. Don't skip it!


2. Deploying to Modern Hosting Platforms

The What and Why

"Deployment" is just a fancy word for putting your website on the internet so people can visit it. While you could technically host a website on your own computer, it's a terrible idea. It would be slow, insecure, and would turn off every time you closed your laptop.

Modern hosting platforms like Netlify, Vercel, and Gatsby Cloud are designed specifically for hosting static sites like the one you just built. They offer incredible benefits:

  • Continuous Deployment (CI/CD): Automatically build and deploy your site whenever you push changes to your Git repository.
  • Global CDN (Content Delivery Network): Your site's files are copied to servers all around the world, so it loads lightning-fast for users no matter where they are.
  • Automatic HTTPS: They handle SSL certificates for you, ensuring your site is secure.
  • Generous Free Tiers: For most personal and small commercial projects, you won't have to pay a dime.

How to Do It: A Git-Based Workflow

The industry-standard approach is to use a Git provider (like GitHub, GitLab, or Bitbucket) to manage your code and trigger deployments.

Step 1: Push Your Project to a Git Repository

If you haven't already, make sure your Gatsby project is a Git repository and push it to a service like GitHub.

bash
# Initialize a Git repository (if you haven't already)
git init
git add .
git commit -m "Initial commit"

# Create a new repository on GitHub and push your code
git remote add origin <YOUR_GITHUB_REPOSITORY_URL>
git branch -M main
git push -u origin main

Step 2: Connect Your Repository to a Hosting Platform (Using Netlify as an Example)

The process is very similar for Vercel and Gatsby Cloud.

  1. Sign up for an account on Netlify, choosing to sign up with your GitHub (or other Git provider) account.
  2. Click the "New site from Git" button.
  3. Choose your Git provider and authorize Netlify to access your repositories.
  4. Select the repository for your Gatsby project.
  5. Configure your build settings. Netlify is smart and usually detects that you're deploying a Gatsby site, pre-filling the settings for you. If not, ensure they are set as follows:
    • Build command: gatsby build
    • Publish directory: public
  6. Click "Deploy site".

That's it! Netlify will now pull your code, run the gatsby build command, and deploy the resulting public folder to its global CDN. From now on, every time you git push to your main branch, a new deployment will be automatically triggered. You've just set up a CI/CD pipeline! 🥳


3. Setting Up Build Webhooks for Automated CMS Updates

The What and Why

If your Gatsby site pulls data from a headless CMS (like Contentful, Sanity, or Strapi), you'll face a new problem. When a content editor publishes a new blog post in the CMS, how does your live website know it needs to update?

You could manually trigger a new build every time, but that's inefficient and frankly, a bit of a drag. This is where webhooks come to the rescue.

A webhook is essentially a notification system. It's a unique URL that, when visited, tells your hosting provider, "Hey, something changed! It's time to rebuild the site." The CMS can be configured to automatically send a request to this URL whenever content is updated.

It’s like setting up a motion sensor in your store. When it detects movement (new content), it automatically sends a signal to the main office (your hosting platform) to restock the shelves (rebuild the site).

How to Do It: Connecting Your CMS

Step 1: Find Your Build Hook URL 🔗

In your hosting platform's dashboard, find the section for build hooks.

  • On Netlify: Go to Site settings > Build & deploy > Continuous deployment > Build hooks. Click "Add build hook", give it a name (e.g., "CMS Update"), and it will generate a unique URL for you.

Step 2: Add the Webhook to Your Headless CMS 🧠

Log in to your headless CMS and find the webhooks settings.

  • On Contentful: Go to Settings > Webhooks. Click "Add Webhook", give it a name, and paste the URL you copied from Netlify into the "URL" field. You can configure it to trigger on specific events, like "Publish" and "Unpublish" for entries.
  • On Sanity: Go to your project's API settings and find the Webhooks section. The process is very similar.

Step 3: Test It!

Now, go into your CMS and make a change—publish a new article or update an existing one. A few seconds later, you should see a new build automatically starting in your Netlify (or Vercel/Gatsby Cloud) dashboard. Magic! ✨ Your content team can now update the website without ever needing to ask a developer for help.


4. Post-Launch: Performance Auditing with Lighthouse

The What and Why

Your site is live! But the job isn't quite done. How do you know if it's really fast and accessible? We need to measure it.

Lighthouse is an open-source, automated tool from Google that audits your web pages for quality. It runs a series of tests against your page and then generates a report on how well it did across several key areas:

  • Performance: How fast does your page load and become interactive?
  • Accessibility: Can people with disabilities use your site?
  • Best Practices: Does your site follow modern web development standards?
  • SEO: Is your site optimized for search engine crawlers?

Running a Lighthouse audit is like getting a report card for your website. It gives you concrete scores and actionable feedback to help you improve.

How to Do It: Running an Audit from Your Browser

The easiest way to run Lighthouse is directly from the Chrome DevTools.

  1. Open your live website in Google Chrome.
  2. Open Chrome DevTools (Cmd + Option + I on Mac, Ctrl + Shift + I on Windows).
  3. Navigate to the "Lighthouse" tab (you may need to click the >> icon to find it).
  4. Choose the categories you want to audit (Performance, Accessibility, etc.) and select whether you're testing the "Mobile" or "Desktop" version. Always test mobile first!
  5. Click "Analyze page load".

After about a minute, Lighthouse will present you with a detailed report with scores from 0-100 for each category. It will also list specific opportunities for improvement, like "Serve images in next-gen formats" or "Ensure text has sufficient color contrast".

Gatsby already takes care of many performance optimizations out of the box, like code splitting and prefetching internal links, which gives you a great starting score. However, things like adding proper alt tags to images or ensuring good color contrast are up to you. Regularly auditing your site helps you catch these issues and maintain a high-quality experience for all users.


📚 References for Extra Reading

Challenge

You are configuring a Gatsby project for continuous deployment on a modern hosting platform that uses a config.toml file for build settings. Your task is to write the content for this configuration file.

Your config.toml file must:

  1. Define the main build context.
  2. Set the build command to the one that creates an optimized, production-ready Gatsby site.
  3. Point the publish directory to the folder generated by the production build command.

Expected result

The configuration file should contain a [build] table. Inside this table, the command key must be set to the string "gatsby build", and the publish key must be set to "public". This correctly instructs the deployment platform to run the production build process and deploy the resulting static files from the public directory.

toml
[build]
  command = "gatsby build"
  publish = "public"
toml

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.