Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 36 ยท Source and Transformer Plugins

Schema Customization

Control the Gatsby GraphQL schema with createSchemaCustomization: type definitions, defaults, @link, @dontInfer, @dateformat and createResolvers to avoid missing-field errors.

By default Gatsby infers its GraphQL schema from the nodes it finds. It samples your data, notices that frontmatter.title is a string and frontmatter.date looks like a date, and builds types to match. This is magical when you start and painful later. The classic symptom: you add a query for frontmatter.cover, no post has a cover yet, and the build fails with "Cannot query field cover". The data is fine; Gatsby simply never saw the field.

Schema customization lets you declare types yourself, so the schema no longer depends on what your sample data happens to contain. This lesson explains inference, how to write type definitions, how to link nodes and how to add computed fields with resolvers. The Gatsby code is read-only; stand-ins run the same logic on plain objects.

How inference works and where it breaks

flowchart LR
  N["Nodes"] --> I["Gatsby samples fields"]
  I --> S["Inferred schema"]
  S --> Q["Your queries"]
  X["Field missing in all nodes"] -.->|"not in schema"| E["Query error"]

If no node has the field, the schema cannot contain it.

Inference problems:

  • Optional fields. A field present on zero nodes does not exist in the schema.
  • Conflicting types. price: 12 on one node and price: "12 USD" on another produces a warning and drops the field.
  • Surprising changes. Adding one differently shaped node changes the schema everyone relies on.

Defining types with createTypes

Use the createSchemaCustomization API in gatsby-node.js:

JavaScript
// gatsby-node.js (real Gatsby, read-only)
exports.createSchemaCustomization = ({ actions }) => {
  const { createTypes } = actions

  createTypes(`
    type MarkdownRemark implements Node {
      frontmatter: Frontmatter!
    }

    type Frontmatter {
      title: String!
      date: Date @dateformat
      draft: Boolean
      tags: [String!]
      cover: File @fileByRelativePath
      author: AuthorsJson @link(by: "name")
    }
  `)
}

Gatsby merges this with what it infers. Now cover always exists in the schema, even when no post has one, and the query returns null instead of failing.

Key pieces of the schema language:

Syntax Meaning
String, Int, Float, Boolean, Date scalar types
[String!] list of non-null strings
title: String! the exclamation mark makes the field required (non-null)
implements Node the type is a top-level node type, with all... root fields
@dontInfer on a type: use only declared fields, ignore the rest
@infer explicitly keep inference on (default)
@dateformat adds formatString, fromNow and difference arguments to a date
@link follow an ID or field value to another node
@fileByRelativePath resolve a relative path to a File node (used for images in front matter)
@mimeTypes(types: [...]) restrict a type to certain MIME types
@childOf(types: [...]) declare a child node type
@proxy(from: "...") expose another field under a new name

Inferred vs explicit schema

Inferred Gatsby guesses from your data
Explicit You declare types with createTypes

Explicit types are stable and self-documenting.

1 / 2

Suppose each post names its author in front matter (author: "Ada Lovelace") and authors live in a JSON file (see transformer plugins). The directive @link(by: "name") tells Gatsby to find the AuthorsJson node whose name equals the value:

GRAPHQL
query {
  allMarkdownRemark {
    nodes {
      frontmatter {
        title
        author { name bio }   # followed through @link
      }
    }
  }
}

Without by, @link matches the node id. This is how you build author pages, related-post lists and category references without duplicating data. It is the schema counterpart of the node IDs you create in sourceNodes.

Computed fields with createResolvers

Sometimes a field should be calculated: a reading time, a full name, a URL. Add it with createResolvers:

JavaScript
// gatsby-node.js (real Gatsby, read-only)
exports.createResolvers = ({ createResolvers }) => {
  createResolvers({
    MarkdownRemark: {
      wordCount: {
        type: "Int",
        resolve(source) {
          return source.rawMarkdownBody.split(/\s+/).filter(Boolean).length
        },
      },
    },
  })
}

Now markdownRemark { wordCount } is queryable. Resolvers run only for the nodes that are queried, so they are cheap for rarely used fields. If a value is needed in a filter or sort, store it with createNodeField in onCreateNode instead, because resolvers are not filterable.

Typegen for TypeScript

With graphqlTypegen: true in gatsby-config.js, Gatsby writes src/gatsby-types.d.ts with a type for every query result. Explicit schema definitions make those types exact, so data.markdownRemark.frontmatter.cover is typed as File | null instead of any.

Stand-in: inferred versus explicit schema

This stand-in is not Gatsby. It infers field types from the first nodes that carry each field, and then compares to an explicit schema that adds a default for a field missing from the data.

JS Stand-in: why optional fields vanish

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

No output.

JS Stand-in: follow a link, compute a field

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

No output.

A pragmatic default for growing sites: declare explicit types for your content models (posts, authors, products) and mark them @dontInfer once they are stable. Let inference keep working for third-party types you do not control.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does querying a field that no node has fail with inference?

    Inference builds the schema from existing data, so absent fields do not exist.
  2. 2. Which API declares types?

    createSchemaCustomization receives actions.createTypes, which accepts schema definition language.
  3. 3. What does @link(by: "name") do?

    It resolves a value to another node, like a foreign key.
  4. 4. When should a computed value be stored with createNodeField instead of a resolver?

    Resolver fields cannot be used in filter and sort, stored fields can.

Summary

  • Gatsby infers the schema from data, which hides optional fields and can change unexpectedly.
  • createSchemaCustomization and createTypes declare stable types; ! makes a field required.
  • Directives such as @link, @dateformat, @fileByRelativePath and @dontInfer shape behavior.
  • createResolvers adds computed fields; store values with createNodeField if you must filter or sort by them.
  • Explicit types also give exact TypeScript types with graphqlTypegen.

Next: StaticImage: Optimized Images Without GraphQL