Sometimes you have that one-off field you need to use. So
you throw it in the frontmatter of your Markdown file and...
then what? The official Gatsby blog theme defines a
BlogPost interface that doesn't include your frontmatter
field! This is intentional because
BlogPost is meant to be
a type that other themes and plugins can depend on, allowing
extension. It's an interface so when you try to
createNodeField it doesn't show up in
fields is on
MdxBlogPost (or some other proxy
type) and not the interface itself.
So what to do?
Inline fragments are the answer.
With inline fragments you can reach deep into the parent
types, whether you chose to
createNodeField or not, to
access your one-off frontmatter field.
Without changing any code in
gatsby-node or other
gatsby-* file, we can use inline fragments to do a
type-switch on the possible return types. Using these type
switches we can reach up into the parent
Mdx node and grab
our frontmatter. This is nice because it makes what we're
doing explicit (that is, extending the data model with new
data that other themes won't depend on) and compatible with
other source types. This part of the query only affects the
types which it declares and the fields will be empty for
Let's say the frontmatter field we want is a
that indicates published status. The frontmatter could look
To clean this up a bit we can put the field we want on our
MdxBlogPost type if we want, since that is a concrete
This simplifies our query while also potentially allowing us
to source this information from a different node (for
example, if we were manually creating MDX content and wanted
it to be represented as a
What happens if we query for a field that doesn't exist in our frontmatter or fields?
We get an error.
We can fix this using the Schema Customization APIs.
This doesn't guarentee we'll get a result. It does guarantee our query won't break the site if someone forgets a date field though!