How to make a GraphQL page query with variables in Gatsby

Oscar de la Hera Gomez
Three flowers that represent Craft CMS, GraphQL and GatsbyJS with the text 'Variable Page Query' beneath it.

A step by step tutorial on making a GraphQL page query with variables in GatsbyJS. Github repository included.

The following tutorial builds off our Open Source starter project and walks you through how to make page queries with variables in Gatsby for pages created programmatically based on entires in a Craft CMS headless CMS gathered through the GraphQL.

We recommend downloading our Open Source project, checking out the tutorial/create-pages-graphql-backend-only branch and carrying out the steps outlined below. All relevant changes can be found on the tutorial/page-queries-with-variables branch.

git clone git@github.com:delasign/typescript-serverless-starter.git

Step One: Import graphql into the template

A screenshot of VSCode showing you how to import GraphQL into a GatsbyJS template in order to execute a variable page query.

At the top of the blogPost.tsx template found in src/templates/blogpost.tsx add the following import.

import { graphql } from 'gatsby'

Step Two: Add the variable page query

A screenshot of VSCode showing you how we added to variable page query to the GatsbyJS function.

Above the export default add the query. A sample one has been provided below:

As shown on line two, the variables are added to the query. These must be passed down through the pageContext from the createPages.

They can then be consumed using a $ as shown on line 4, with $slug being the relevant example.

Step Three: Update the template props type

A screenshot of VSCode of our template with the updated props type.

Gatsby page queries are offered to the page via data available through the props. Update your props type (BlogPostPageContext) to include the data model.

Step Four: Prepare for consumption

A screenshot of VSCode showing how we added data to the props and page in order to verify the results.

Add data to the props that can be consumed.

We also unpacked them and printed them on the page to verify that it worked.

Step Five: Verify

A screenshot of Chome showing the meta title, meta description, slug and uri of a sample page produced programatically using this tutorial.

In Terminal, run yarn start at your project directory to execute the changes and navigate to a page that was programmatically created to witness the meta data.

Any Questions?

We are actively looking for feedback on how to improve this resource. Please send us a note to inquiries@delasign.com with any thoughts or feedback you may have.

delasign logo

Book a Free Consultation.

An icon of an email.

Click here to email us.

Fill in the details below to book a free consultation or to let us know about something else. Whatever it is, we are here to help.

How can we help you ?

Contact Details