Static Site Generation (SSG) with Gatsby and GraphQL: A Comprehensive Guide

Table of Contents
Big thanks to our contributors those make our blogs possible.

Our growing community of contributors bring their unique insights from around the world to power our blog. 

Static Site Generation (SSG) marries the performance and security benefits of pre-rendered HTML with the power of modern JavaScript frameworks. Gatsby, a React-based SSG, leverages GraphQL as its data layer—allowing you to source content from Markdown files, CMSs, APIs, databases, and more, then build lightning-fast, SEO-friendly websites. In this detailed guide, we’ll explore:

  1. Why SSG? Benefits and use cases
  2. Gatsby’s Architecture: How Gatsby uses GraphQL under the hood
  3. Getting Started: Project setup and essential plugins
  4. Data Sourcing: Querying content with GraphQL
  5. Dynamic Pages: Programmatic page creation
  6. Performance Optimizations: Image handling, code splitting, lazy loading
  7. Deployment: Hosting your Gatsby site
  8. Advanced Tips: Previewing drafts, incremental builds, caching

By the end, you’ll have a blueprint for building and deploying high-performance static sites with Gatsby and GraphQL.

1. Why Choose SSG and Gatsby?

Benefits of Static Site Generation

  • Blazing Fast Performance: HTML is pre-rendered at build time—no server-side rendering on each request.
  • Enhanced Security: No runtime server or database reduces attack surface.
  • SEO-Friendly: Fully rendered pages on first load aid search-engine indexing.
  • Scalability: Serve static assets via CDN without complex backend infrastructure.

Why Gatsby?

  • Rich Plugin Ecosystem: Over 2,000 plugins to source data, optimize images, add PWA features, and more.
  • GraphQL Data Layer: Uniform API to query data from multiple sources.
  • React-Based: Build interactive UIs with familiar React components.
  • Image Optimization: Built-in support for responsive, lazy-loaded images via gatsby-plugin-image.
  • Progressive Web App (PWA): Default service-worker setup for offline support.

2. Gatsby’s Architecture and GraphQL

Under the hood, Gatsby’s build process comprises three key phases:

  1. Source and Transform Data: Plugins fetch data from sources (Markdown, headless CMS, REST/GraphQL APIs).
  2. GraphQL Data Layer: All sourced data is made available via a unified GraphQL schema.
  3. Create Pages: Your React templates query this data and generate static HTML/JS at build time.

GraphQL allows you to specify exactly which data fields you need:

graphqlCopyEditquery BlogPostBySlug($slug: String!) {
  markdownRemark(fields: { slug: { eq: $slug } }) {
    frontmatter {
      title
      date(formatString: "MMMM DD, YYYY")
      author
    }
    html
  }
}

3. Getting Started with Gatsby

Prerequisites

  • Node.js (≥14 LTS)
  • npm or Yarn

Project Initialization

bashCopyEditnpx gatsby new gatsby-ssg-graphql
cd gatsby-ssg-graphql

Essential Plugins

Install core plugins:

bashCopyEditnpm install gatsby-source-filesystem gatsby-transformer-remark gatsby-plugin-image gatsby-plugin-sharp gatsby-transformer-sharp

Configure in gatsby-config.js:

jsCopyEditmodule.exports = {
  siteMetadata: {
    title: `My Gatsby SSG Site`,
    description: `A static site powered by Gatsby and GraphQL`,
    author: `@yourhandle`,
  },
  plugins: [
    `gatsby-plugin-image`,
    `gatsby-plugin-sharp`,
    `gatsby-transformer-sharp`,
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `posts`,
        path: `${__dirname}/content/posts`,
      },
    },
    `gatsby-transformer-remark`,
  ],
};

4. Sourcing and Querying Data with GraphQL

Organizing Content

Create Markdown files in content/posts/:

markdownCopyEdit---
title: "Hello Gatsby"
date: "2025-06-01"
author: "Jane Doe"
---

Welcome to your first **Gatsby** post!

GraphQL Explorer

Run gatsby develop and visit http://localhost:8000/___graphql to explore your schema.

Sample Page Query

In src/templates/blog-post.js:

jsxCopyEditimport React from "react";
import { graphql } from "gatsby";

export default function BlogPost({ data }) {
  const post = data.markdownRemark;
  return (
    <article>
      <h1>{post.frontmatter.title}</h1>
      <p><em>{post.frontmatter.date} — {post.frontmatter.author}</em></p>
      <div dangerouslySetInnerHTML={{ __html: post.html }} />
    </article>
  );
}

export const query = graphql`
  query($slug: String!) {
    markdownRemark(fields: { slug: { eq: $slug } }) {
      frontmatter { title date author }
      html
    }
  }
`;

5. Programmatic Page Creation

In gatsby-node.js, create pages dynamically:

jsCopyEditconst path = require("path");
exports.createPages = async ({ graphql, actions }) => {
  const { createPage } = actions;
  const result = await graphql(`
    {
      allMarkdownRemark {
        nodes {
          fields { slug }
        }
      }
    }
  `);
  result.data.allMarkdownRemark.nodes.forEach(node => {
    createPage({
      path: node.fields.slug,
      component: path.resolve(`./src/templates/blog-post.js`),
      context: { slug: node.fields.slug },
    });
  });
};

// Add slug field
exports.onCreateNode = ({ node, actions, getNode }) => {
  const { createNodeField } = actions;
  if (node.internal.type === "MarkdownRemark") {
    const slug = `/posts/${node.frontmatter.title.replace(/\s+/g, "-").toLowerCase()}/`;
    createNodeField({ node, name: "slug", value: slug });
  }
};

6. Performance Optimizations

  • Image Handling: Use <GatsbyImage> with gatsby-plugin-image for responsive, lazy-loaded images.
  • Code Splitting: Gatsby automatically splits JS bundles per page.
  • Preload Critical Resources: Use gatsby-plugin-preload-link-crossorigin for fonts.
  • Minification and Compression: Enabled by default in production builds.

7. Deployment

Build your site:

bashCopyEditgatsby build

Deploy to popular hosts:

  • Gatsby Cloud: Optimized for previews and incremental builds.
  • Netlify / Vercel: Drag-and-drop or Git integration with continuous deployment.
  • Amazon S3 + CloudFront: Serve static assets via CDN.

8. Advanced Tips

  • Preview Draft Content: Use gatsby-source-contentful or a webhook to trigger builds when content updates.
  • Incremental Builds: Gatsby Cloud and Netlify incremental builds only rebuild changed pages.
  • GraphQL Fragments: Reuse common query parts: graphqlCopyEditfragment PostFields on MarkdownRemark { frontmatter { title date } fields { slug } }

Conclusion

Gatsby’s SSG workflow, powered by a flexible GraphQL data layer, enables you to build ultra-fast, SEO-optimized static websites that pull content from nearly any source. By following this guide—from project setup and content sourcing to dynamic page generation and performance tuning—you’ll have a robust foundation for launching modern, scalable static sites. Start experimenting with plugins, customize your GraphQL schema, and leverage Gatsby’s rich ecosystem to deliver outstanding web experiences.

Let's connect on TikTok

Join our newsletter to stay updated

Sydney Based Software Solutions Professional who is crafting exceptional systems and applications to solve a diverse range of problems for the past 10 years.

Share the Post

Related Posts