Gatsby: TypeError: Cannot read property 'frontmatter' of null

Created on 17 Feb 2018  ·  23Comments  ·  Source: gatsbyjs/gatsby

Description

Environment

Gatsby version: 1.9.158
Node.js version: 8.9.3
Operating System: MacOS X

File contents (if changed):

gatsby-config.js:
resolve: gatsby-transformer-remark,

package.json:

"dependencies": {
"gatsby": "^1.9.158",
"gatsby-link": "^1.6.34",
"gatsby-plugin-canonical-urls": "^1.0.12",
"gatsby-plugin-react-helmet": "^2.0.3",
"gatsby-plugin-sharp": "^1.6.27",
"gatsby-remark-images": "^1.5.43",
"gatsby-remark-prismjs": "^1.2.15",
"gatsby-source-filesystem": "^1.5.16",
"gatsby-transformer-remark": "^1.7.30",
...
}

gatsby-node.js:
gatsby-browser.js:
gatsby-ssr.js:

Actual result

I write my pages in Markdown. When I forgot the leading slash in the frontmatter's path property, like so:

path: about-me

then I see an error in the browser in yarn develop:

TypeError: Cannot read property 'frontmatter' of null

This error message is not helpful at all. It cost me lots of time.

Expected behavior

Gatsby should show a useful error message like

path property in frontmatter of file XYZ must have a leading slash

Steps to reproduce

1.

2.

3.

...

stale? bug

Most helpful comment

I just resolved this same issue by adding a leading / in the path of my latest post, after much struggle trying to decipher its meaning and finally landing on this thread! Just thought I'd throw my +1 in for this being a rather unhelpful error :)

In case it's helpful, on my local everything worked fine except for the URL with the improper path value (throwing no errors except in-browser when I visited the specific address), but it was blocking Netlify's site compile completely.

All 23 comments

I don't know why the lack of a leading slash would cause anything to fail. It's certainly not a requirement. Is your site public? Perhaps we could take a look at it? Sorry for the mysterious error!

My code is not public, but I will create new site and reproduce the issue there.

I get this all the time working on React blog. It's pretty frustrating. To reproduce, clone reactjs.org, open a blog post and start editing it. Eventually you'll hit this.

v2 is better at this but still not perfect. The problem is basically a timing issue where queries can sometimes be run when data is in process of updating. The plan is to add xstate to ensure that data is finished processing before we run queries on the updated data.

It is a really obnoxious bug though :-\

I just resolved this same issue by adding a leading / in the path of my latest post, after much struggle trying to decipher its meaning and finally landing on this thread! Just thought I'd throw my +1 in for this being a rather unhelpful error :)

In case it's helpful, on my local everything worked fine except for the URL with the improper path value (throwing no errors except in-browser when I visited the specific address), but it was blocking Netlify's site compile completely.

I put the / in front of the path for my new post but it's not working. Here is my code for the file that it isn't liking:
```import React from 'react'
import Helmet from 'react-helmet'
import { graphql } from 'gatsby'

// import '../css/blog-post.css';

export default function Template({ data }) {
const { markdownRemark: post } = data
return (


Your Blog Name - ${post.frontmatter.title}} />

{post.frontmatter.title}


className="blog-post-content"
dangerouslySetInnerHTML={{ __html: post.html }}
/>


)
}

export const pageQuery = graphql query BlogPostByPath($path: String!) { markdownRemark(frontmatter: { path: { eq: $path } }) { html frontmatter { date(formatString: "MMMM DD, YYYY") path title } } }
```

Any help on this would be really great.

Still occurs to me. I'm writing a blog post right now, and when it became long enough I started to get these errors every few minutes. Saving the post a few times (or a few dozen times) usually fixes it, but it's really annoying.

I'm using a query almost identical to the one used by @RedHoodJT1988 above, except I'm not using a path property. and every property in the frontmatter is quoted. So I don't think it has anything to do with path having a leading slash.

looks like we can use workaround like preparing synthetic field which will match to asked path

let prefix = '/'

createNodeField({
  node,
  name: `syntheticPath`,
   value: `${prefix}${node.frontmatter.path}`, // lead custom filed to necessary structure to match to it further
})

update your createPage properties to new field

graphql(`
      {
        allMarkdownRemark {
          edges {
            node {
              fields {
                syntheticPath
              }
            }
          }
        }
      }
    `).then(result => {
         result.data.allMarkdownRemark.edges.forEach(({ node }) => {
           createPage({
             path: node.fields.syntheticPath, // apply path with new value
             component,
           })
        })
     })

and in necessary template

export const pageQuery = graphql`
  query($path: String!) {
    markdownRemark(fields: { syntheticPath: { eq: $path } }) {
    // list of asked fields
    }
 }
`

also thanks for it we can use any nested rotes parent/child/markdown_uniq_name

Hiya!

This issue has gone quiet. Spooky quiet. 👻

We get a lot of issues, so we currently close issues after 30 days of inactivity. It’s been at least 20 days since the last update here.

If we missed this issue or if you want to keep it open, please reply here. You can also add the label "not stale" to keep this issue open!

Thanks for being a part of the Gatsby community! 💪💜

I'm using gatsby advanced starter and I got this error. If I compiled twice (exit and do gatsby develop again) this error goes away. But it works only for some time. If there is a permanent solution it would be good.

I hit this issue today.
I changed from "gatsby": "^2.1.4" to "gatsby": "^1.x", and I don't have it anymore. Reading the comments here I can't understand why this works.

I observed it was happening when I was renaming content/project/folders (I'm reusing portfolio-emma starter). post.frontmatter & post was null for the project with modified folder name in .cache/app.js. Deleting .cache and running dev script fixes it but it is a bit annoying.
I've added the .cache deletion to my dev script for the moment, is there a better solution?

Thank you so much @stefanwille and @tatwater for your help!!!

Adding that sneaky missing forward slash made it work!

Hiya!

This issue has gone quiet. Spooky quiet. 👻

We get a lot of issues, so we currently close issues after 30 days of inactivity. It’s been at least 20 days since the last update here.

If we missed this issue or if you want to keep it open, please reply here. You can also add the label "not stale" to keep this issue open!

As a friendly reminder: the best way to see this issue, or any other, fixed is to open a Pull Request. Check out gatsby.dev/contribute for more information about opening PRs, triaging issues, and contributing!

Thanks for being a part of the Gatsby community! 💪💜

I was getting the TypeError: Cannot read property 'frontmatter' of null error in the browser for several hours then it switched to TypeError: Cannot read property 'markdownRemark' of undefined. Then suddenly the page loaded. Interspersed throughout that were about a million or so restarts. 🤷‍♂

Hey again!

It’s been 30 days since anything happened on this issue, so our friendly neighborhood robot (that’s me!) is going to close it.

Please keep in mind that I’m only a robot, so if I’ve closed this issue in error, I’m HUMAN_EMOTION_SORRY. Please feel free to reopen this issue or create a new one if you need anything else.

As a friendly reminder: the best way to see this issue, or any other, fixed is to open a Pull Request. Check out gatsby.dev/contribute for more information about opening PRs, triaging issues, and contributing!

Thanks again for being part of the Gatsby community!

Bit of an avoiding the problem solution, but to fix this I contained the entire function and return statement in an if statement like:
if(frontmatter !== null) { }

and then put an else statement else return null, it seemed like it was trying to produce a blog post from a null markdown after producing the actual blog posts. Probably my dodgy code - but it builds

I just resolved this same issue by adding a leading / in the path of my latest post, after much struggle trying to decipher its meaning and finally landing on this thread! '

This was the solution for me as well. Wanted to signal boost this because it seems to be the solution on this thread that reliably works.

First off, Gatsby is amazing.

Second, I'm having the same issue as everyone else here, but it's a bit strange. I am only seeing this issue on incremental or subsequent changes to a md file after I've initially built. It's pretty frustrating because if i want to live-edit a blog post, I have to make my edits and then manually run a restart.

exports.onCreateNode = ({ node, getNode, actions }) => {
  const { createNodeField } = actions
  if (node.internal.type === `MarkdownRemark`) {
    const slug = createFilePath({ node, getNode })

    createNodeField({
      node,
      name: `slug`,
      value: slug,
    })
  }
}


exports.createPages = async ({ actions, graphql, reporter }) => {
  const { createPage } = actions
  const blogPostTemplate = path.resolve("src/templates/blog.tsx")
  const tagTemplate = path.resolve("src/templates/tags.tsx")
  const result = await graphql(`
    query getContent {
      posts: allMarkdownRemark(
        sort: { order: DESC, fields: [frontmatter___date] }
        limit: 2000
      ) {
        edges {
          node {
            fields {
              slug
            }
            frontmatter {
              tags
              title
              date
            }
          }
        }
      }
      tags: allMarkdownRemark(limit: 2000) {
        group(field: frontmatter___tags) {
          fieldValue
        }
      }
    }
  `)
  // handle errors
  if (result.errors) {
    reporter.panicOnBuild(
      `Error while running GraphQL query. ${JSON.stringify(result.errors)}`
    )
    return
  }
  const posts = result.data.posts.edges
  posts.forEach(({ node }, index) => {
    const prev = index === 0 ? false : posts[index - 1].node
    const next = index === posts.length - 1 ? false : posts[index + 1].node

    createPage({
      path: node.fields.slug,
      component: blogPostTemplate,
      context: {
        prev,
        next,
      },
    })
  })

  const tags = result.data.tags.group
  tags.forEach(tag => {
    createPage({
      path: `/tags/${_.kebabCase(tag.fieldValue)}/`,
      component: tagTemplate,
      context: {
        tag: tag.fieldValue,
      },
    })
  })
}

./src/content/blog/writing-typescript.md (note the path frontmatter):

---
title: My First Post on Typescript
date: 2019-07-10
path: /blog/writing-typescript/
---

This is my first post on TypeScript

Should be noted that on first pass, and first load, things are great. Only errors out on a code change or recompile.

I should note also that I am using gatsby-plugin-remove-trailing-slashes

I'm not really doing anything else out of the ordinary, but I can share more of my config and setup if it's helpful.

Ah, just to follow up:

Looks like that gatsby-plugin-remove-trailing-slashes was, in fact, causing some issues for me. I removed that and changed the format to something like this in my frontmatter and it seemed to work. Needed both the leading and trailing slash.

path: /projects/lego/

Bit of an avoiding the problem solution, but to fix this I contained the entire function and return statement in an if statement like:
if(frontmatter !== null) { }

and then put an else statement else return null, it seemed like it was trying to produce a blog post from a null markdown after producing the actual blog posts. Probably my dodgy code - but it builds

For now, I've solved it like this too. thanks @tomwilliamfranklin

I was facing the same issue, so what i did, i created another post with same content as previous post(post which was showing cannot read property of null) but with different path and rerun the code, then the new post which i created was working fine and the previous post which was showing the error was still showing the error so i deleted it. now everything is working fine.
This worked out for me :)

Tried editing the existing post by adding "/" but still didn't help.
The only solution was to delete the old blog and add a new one.

Was this page helpful?
1 / 5 - 2 ratings