Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 36 ยท Getting Started

gatsby-config and the Node APIs

Configure a Gatsby site with siteMetadata and plugins, then hook into the build with gatsby-node APIs such as onCreateNode, createPages and sourceNodes.

Two files control how a Gatsby site is built. gatsby-config.js is declarative: it says what the site is and which plugins it uses. gatsby-node.js is imperative: it exports functions that Gatsby calls at specific moments in the build, so you can add data, change nodes and create pages. Understanding the difference makes everything later in this track easier.

All Gatsby code in this lesson is read-only; stand-ins show the same patterns in runnable JavaScript.

gatsby-config.js

The config exports an object. These keys appear most often:

JavaScript
// gatsby-config.js (real Gatsby, read-only)
module.exports = {
  siteMetadata: {
    title: "Coffee Notes",
    description: "Notes about brewing.",
    siteUrl: "https://coffee.example.com",
  },
  pathPrefix: "/blog",       // only when hosted under a sub-path
  trailingSlash: "always",   // "always" | "never" | "ignore"
  graphqlTypegen: true,      // generate TypeScript types for queries
  plugins: [
    "gatsby-plugin-image",
    "gatsby-plugin-sharp",
    "gatsby-transformer-sharp",
    {
      resolve: "gatsby-source-filesystem",
      options: { name: "posts", path: `${__dirname}/content/posts` },
    },
  ],
}
  • siteMetadata is global data about the site. It becomes available in GraphQL as site.siteMetadata (see page queries and useStaticQuery). It is public, so no secrets.
  • plugins is an ordered list. Each entry is either a string (no options) or an object with resolve and options.
  • trailingSlash decides whether URLs end with /. Pick one policy and keep it; it avoids duplicate-content issues.
  • graphqlTypegen writes TypeScript types for your queries when you use TypeScript.

Because the file is plain Node code, you can compute values, read environment variables or add plugins conditionally.

What plugins are

A plugin is an npm package (or a local folder in plugins/) that implements Gatsby APIs. There are three common kinds:

  • Source plugins create nodes from some data source (lesson).
  • Transformer plugins turn one node type into another, for example a Markdown file into structured post data (lesson).
  • Functional plugins add features such as image processing, sitemaps, manifests or analytics.

gatsby-node.js

Gatsby calls exported functions from this file when specific events happen. Each receives an object with actions (functions that change the build), graphql (a function that runs queries), reporter (for logging) and other helpers:

JavaScript
// gatsby-node.js (real Gatsby, read-only)
exports.onCreateNode = ({ node, actions }) => {
  const { createNodeField } = actions
  if (node.internal.type === "MarkdownRemark") {
    createNodeField({ node, name: "slug", value: "/" + node.frontmatter.title.toLowerCase().replace(/\s+/g, "-") + "/" })
  }
}

exports.createPages = async ({ graphql, actions, reporter }) => {
  const { data, errors } = await graphql(`
    { allMarkdownRemark { nodes { id fields { slug } } } }
  `)
  if (errors) {
    reporter.panicOnBuild("Query failed", errors)
    return
  }
  data.allMarkdownRemark.nodes.forEach((node) => {
    actions.createPage({
      path: node.fields.slug,
      component: require.resolve("./src/templates/post.js"),
      context: { id: node.id },
    })
  })
}

The most important APIs, in the order they run:

API Purpose
onPreInit / onPreBootstrap setup before the build begins
sourceNodes create nodes from external data
onCreateNode react to every node created; add fields
createSchemaCustomization declare GraphQL types (lesson)
createPages create pages from data (lesson)
onCreatePage change or delete pages as they are created
onPostBuild run code after the build, for example write extra files
flowchart LR
  A["onPreInit"] --> B["sourceNodes"]
  B --> C["onCreateNode<br/>(per node)"]
  C --> D["createSchemaCustomization"]
  D --> E["createPages"]
  E --> F["queries and render"]
  F --> G["onPostBuild"]

Simplified order. Data first, then schema, then pages, then rendering.

Stand-in: a plugin runner

This stand-in is not Gatsby. It runs a list of plugin objects against lifecycle hooks, which is the same idea as Gatsby's API runner: every plugin may implement any hook, and Gatsby calls them in order.

JS Stand-in: lifecycle hooks and plugins

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice how the slugger plugin never knows who created the nodes, and page-maker never knows where slugs came from. Plugins cooperate only through the shared node store.

Stand-in: validating a config

A config mistake often shows up as a confusing error later. This stand-in normalizes the plugins array the same way Gatsby accepts both strings and objects, and reports problems early.

JS Stand-in: normalize and validate plugins

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Order matters for plugins that depend on each other. A transformer must run after the source that creates the nodes it transforms. If data seems to be missing, check the order and the options (a wrong path is the number one cause).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What kind of file is gatsby-config.js?

    The config exports an object with siteMetadata, plugins and other options. Lifecycle functions live in gatsby-node.js.
  2. 2. Which API creates pages from data?

    createPages receives actions.createPage, which you call once per page.
  3. 3. Why is siteMetadata unsuitable for secrets?

    siteMetadata becomes queryable data that can end up in page output, so it must contain only public values.
  4. 4. A source plugin and a transformer plugin must be ordered how?

    Transformers react to nodes that sources create, so the nodes must exist.

Summary

  • gatsby-config.js declares metadata, URL policy and plugins; it is plain Node code.
  • gatsby-node.js exports hooks such as sourceNodes, onCreateNode and createPages.
  • Plugins are npm packages or local folders implementing those same hooks.
  • Plugins cooperate through nodes: sources create them, transformers and your code enrich them.
  • Fix config problems by checking plugin order and option values first.

Next: Pages and File System Routing