Search code examples
gatsbynetlifynetlify-cms

How to get the slug to show up in graphql using NetlifyCMS and Gatsby?


When adding netlify cms to a site how does one go about getting the slug to show up in graphql? I have one collection for a blog post and everything shows up except the slug:

backend:
  name: git-gateway
  branch: master # Branch to update (optional; defaults to master)

media_folder: static/images
public_folder: /images

collections:
  - name: "blog"
  label: "Blog"
  folder: "content/blogPost"
  create: true
  slug: "{{year}}-{{month}}-{{day}}-{{slug}}"
  fields: # The fields for each document, usually in front matter
    - { label: "Layout", name: "layout", widget: "hidden", default: "blog" }
    - { label: "Title", name: "title", widget: "string" }
    - { label: "Publish Date", name: "date", widget: "datetime" }
    - { label: "Featured Image", name: "thumbnail", widget: "image" }
    - { label: "Body", name: "body", widget: "markdown" }

And here is my graphql query: enter image description here


Solution

  • The slug in the GraphQL query is not part of the frontmatter of the fields in the config.yml. These slug fields are not related. The one you are referring to in your query is from the node in Gatsby.

    The fields value in the GraphQL query above is missing from your node. This would have to be passed using the gatsby-node.js config by adding it as in this example:

    const { createFilePath } = require('gatsby-source-filesystem')
    
    exports.onCreateNode = ({ node, boundActionCreators, getNode }) => {
      const { createNodeField } = boundActionCreators
    
      if (node.internal.type === `MarkdownRemark`) {
        const value = createFilePath({ node, getNode })
        createNodeField({
          name: `slug`,
          node,
          value,
        })
      }
    }