Learn Gatsby · 10/12

Extending Gatsby Capabilities with Plugins

6 min read

Extending Gatsby Capabilities with Plugins 🚀

Welcome back! So, you've got the basics of your Gatsby site up and running. It's fast, it's modern, but maybe it feels a little... plain. You want to add more power, more features, without having to build everything from scratch. This is where the magic of Gatsby plugins comes in.

The Problem: Building complex functionalities like analytics, image optimization, or offline support from the ground up is time-consuming and requires a lot of specialized knowledge.

The Solution: Gatsby's rich plugin ecosystem allows you to tap into a vast library of pre-built functionalities. Think of plugins as pre-packaged features you can easily install and configure to extend your site's capabilities.


🗺️ 1. Navigating the Gatsby Plugin Library

Imagine walking into a massive, well-organized library. Instead of books, the shelves are lined with thousands of plugins, each designed to solve a specific problem. That's the Gatsby Plugin Library for you!

What is the Gatsby Plugin Library?

It's the official, centralized repository where you can discover and explore over 3,000 plugins developed by the Gatsby team and the community. It's your go-to resource for finding the right tool for the job.

How to Find the Right Plugin:

  1. Search is Your Best Friend: The library has a powerful search bar. Start by typing in keywords related to the functionality you need, like "analytics," "SEO," or "sitemap."
  2. Sort by Popularity: The plugins are sorted by popularity by default, which is a great way to see what others in the community are using and trust.
  3. Read the Documentation: Each plugin has its own page with detailed instructions on how to install and configure it. Always read this thoroughly before installing.

Fun Fact: The sheer number of plugins available is a testament to the strength and activity of the Gatsby community. It's like having thousands of developers who've already solved problems you might be facing.

Installing and Configuring a Plugin:

Getting a plugin up and running is typically a two-step process:

  1. Installation: You use your package manager (npm or yarn) to install the plugin as a dependency in your project.

    bash
    npm install gatsby-plugin-name
  2. Configuration: You then add the plugin to the plugins array in your gatsby-config.js file. Some plugins require additional configuration options.

    javascript
    // gatsby-config.js
    module.exports = {
      plugins: [
        'gatsby-plugin-react-helmet', // A plugin with no options
        {
          resolve: `gatsby-source-filesystem`, // A plugin with options
          options: {
            name: `images`,
            path: `${__dirname}/src/images`,
          },
        },
      ],
    }

A Word of Caution: Any time you make changes to your gatsby-config.js file, you need to restart your development server for the changes to take effect. It's a common "gotcha" for new developers!


📊 2. Integrating Third-Party Analytics (Google Analytics/Tag Manager)

You've built a beautiful website, but how do you know if anyone is actually visiting it? This is where analytics tools like Google Analytics and Google Tag Manager come in.

The Problem: Manually adding the tracking scripts for these services to every page of your site is tedious and prone to errors.

The Solution: Gatsby plugins to the rescue! There are dedicated plugins that make integrating these services a breeze.

Google Analytics

gatsby-plugin-google-gtag is a popular choice for adding Google Analytics to your site.

Installation:

bash
npm install gatsby-plugin-google-gtag

Configuration:

In your gatsby-config.js:

javascript
// gatsby-config.js
module.exports = {
  plugins: [
    {
      resolve: `gatsby-plugin-google-gtag`,
      options: {
        // Your tracking IDs
        trackingIds: [
          "GA_TRACKING_ID", // Google Analytics / GA
        ],
        // This object gets passed directly to the gtag config command
        gtagConfig: {
          anonymize_ip: true,
          cookie_expires: 0,
        },
        // This object is used for configuration specific to this plugin
        pluginConfig: {
          // Puts tracking script in the head instead of the body
          head: false,
        },
      },
    },
  ],
}

Google Tag Manager

For those who want more advanced tracking capabilities, gatsby-plugin-google-tagmanager is the way to go.

Installation:

bash
npm install gatsby-plugin-google-tagmanager

Configuration:

In your gatsby-config.js:

javascript
// gatsby-config.js
module.exports = {
  plugins: [
    {
      resolve: "gatsby-plugin-google-tagmanager",
      options: {
        id: "YOUR_GOOGLE_TAG_MANAGER_ID",

        // Include GTM in development.
        // Defaults to false meaning GTM will only be loaded in production.
        includeInDevelopment: false,

        // datalayer to be pushed to GTM
        defaultDataLayer: { platform: "gatsby" },
      },
    },
  ],
};

Pro Tip: It's generally a good practice to only enable analytics in your production environment to avoid skewing your data with your own development activity.


✍️ 3. Typography and Web Font Optimization Plugins

The right typography can make or break your website's design. But loading custom fonts can sometimes slow down your site.

The Problem: Large font files can increase your site's initial load time, leading to a poor user experience.

The Solution: Gatsby offers plugins to efficiently load and manage web fonts, ensuring your site stays fast.

A common approach is to use a plugin like gatsby-plugin-web-font-loader.

Installation:

bash
npm install gatsby-plugin-web-font-loader

Configuration:

This plugin allows you to load fonts from various sources like Google Fonts, Typekit, and self-hosted files.

Here's an example of loading fonts from Google Fonts:

javascript
// gatsby-config.js
module.exports = {
  plugins: [
    {
      resolve: 'gatsby-plugin-web-font-loader',
      options: {
        google: {
          families: ['Droid Sans', 'Droid Serif']
        }
      }
    }
  ]
}

What happens under the hood? This plugin will asynchronously load the fonts, which means it won't block the rendering of the rest of your page. This leads to a much faster perceived loading time for your users.


📱 4. Building a Progressive Web App (PWA): Manifests and Offline Support

Wouldn't it be cool if your website could work even when the user is offline? Or if they could add it to their home screen like a native app? That's the power of Progressive Web Apps (PWAs).

The Problem: Turning a website into a PWA involves several technical steps, including creating a web app manifest and setting up a service worker for offline caching.

The Solution: Gatsby provides two essential plugins that handle the heavy lifting for you: gatsby-plugin-manifest and gatsby-plugin-offline.

gatsby-plugin-manifest

This plugin generates a manifest.webmanifest file for your site. This file provides information about your application (like its name, icon, and theme color) to the browser, allowing users to "install" it on their device.

Installation:

bash
npm install gatsby-plugin-manifest

Configuration:

In your gatsby-config.js:

javascript
// gatsby-config.js
module.exports = {
  plugins: [
    {
      resolve: `gatsby-plugin-manifest`,
      options: {
        name: `GatsbyJS`,
        short_name: `GatsbyJS`,
        start_url: `/`,
        background_color: `#f7f0eb`,
        theme_color: `#a2466c`,
        display: `standalone`,
        icon: `src/images/icon.png`, // This path is relative to the root of the site.
      },
    },
  ],
}

gatsby-plugin-offline

This plugin creates a service worker for you that will automatically cache your site's pages and assets. This allows your site to work offline or on flaky network connections.

Installation:

bash
npm install gatsby-plugin-offline

Configuration:

Simply add gatsby-plugin-offline to your gatsby-config.js. It's important to list this plugin after gatsby-plugin-manifest.

javascript
// gatsby-config.js
module.exports = {
  plugins: [
    `gatsby-plugin-manifest`,
    `gatsby-plugin-offline`, // This should be the last plugin in the array
  ],
}

Real-world Scenario: Imagine a user is browsing your blog on the subway. They lose their internet connection, but because you've turned your site into a PWA, they can continue reading the articles they've already visited without any interruption. That's a fantastic user experience!


📚 Further Reading & Resources

Challenge

Challenge: Advanced Gatsby Plugin Configuration

You are tasked with setting up a gatsby-config.js file for a new project that requires Progressive Web App (PWA) capabilities, optimized web font loading, and production-only analytics.

Modify the provided gatsby-config.js to meet all of the following requirements:

  1. Web Font Loading: Integrate gatsby-plugin-web-font-loader to asynchronously load the following Google Fonts:

    • Roboto with weights 400 and 700.
    • Montserrat with weight 600.
  2. PWA Manifest: Add gatsby-plugin-manifest to generate the web app manifest. Configure it with the following options:

    • name: "Gatsby Pro Site"
    • short_name: "ProSite"
    • start_url: "/"
    • background_color: "#663399"
    • theme_color: "#663399"
    • display: "minimal-ui"
    • icon: "src/images/gatsby-icon.png"
  3. Offline Support: Add gatsby-plugin-offline to enable service worker functionality. You must place this plugin in the correct order relative to the other PWA plugin for it to function correctly.

  4. Analytics: Configure gatsby-plugin-google-tagmanager for analytics.

    • Set its id option to 'GTM-ABC123Z'.
    • This plugin should only be active in the production environment. Use a standard Node.js environment variable check (process.env.NODE_ENV === 'production') to conditionally include this plugin.

Expected result

The plugins array in module.exports should contain correctly configured objects for gatsby-plugin-web-font-loader and gatsby-plugin-manifest.

The configuration for gatsby-plugin-web-font-loader must include an options object with a google property, which in turn has a families array containing the strings 'Roboto:400,700' and 'Montserrat:600'.

The configuration for gatsby-plugin-manifest should have an options object matching all the specified key-value pairs (name, short_name, start_url, etc.).

The gatsby-plugin-offline configuration (which can be just the string 'gatsby-plugin-offline') must be the last item in the plugins array to ensure it correctly processes the manifest file.

The gatsby-plugin-google-tagmanager configuration should be added conditionally. The final code should use a technique like the spread syntax (...) with a ternary operator on the isProduction variable to ensure this plugin is only included in the array when the condition is met. Its options object must contain the specified id.

javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.