How To Dynamically Build Product Pages With Shopify & Gatsby

When I first started dabbling with the idea of building a statically generated ecommerce site with Gatsby and Shopify, I was under the impression that this would be very laborious task for stores that have more than a few products. I had imaged created a directory inside of pages called products (src/pages/products/), and manually creating a file for each and every product that exists in the Shopify admin.

I was convinced that there must be a better way, and I had heard Scott Tolinski of Syntax.fm mention that he made a few tutorials on Gatsby and specifically a couple with Gatsby and Shopify. So, I turned to Level Up Tutorials for help. I quickly discovered that a page for each product can be dynamically built by harnessing the power of the Gatsby createPage API and Shopify's GraphQL Storefront API.

Just a little bit of configuration in the gatsby-node.js file and we are well on our way to generating a page per product returned by the GraphQL query.


const path = require('path');

exports.createPages = async({
  graphql,
  actions: { createPage }
}) => {
  const pages = await graphql(`
  {
    allShopifyProduct {
      edges {
        node {
          id
          handle
        }
      }
    }
  }  
  `);

  pages.data.allShopifyProduct.edges.forEach(edge => {
    createPage({
      path: `/products/${edge.node.handle}`,
      component: path.resolve(`./src/templates/ProductPage.js`),
      context: {
        id: edge.node.id,
        handle: edge.node.handle
      },
    })
  })
}