Skip to main content

Decoupling Drupal Commerce with Gatsby

Welcome to yet another blog post! In this article, we will learn how to decouple Drupal Commerce with Gatsby to build an e-commerce site that includes product detail pages, product listing pages, and much more. 

Let’s get started! 

Decoupling Drupal Commerce with Gatsby

We will be covering the checkout functionality our next blog post.

Prerequisite

You should have some prior knowledge of Drupal Commerce and Gatsby. 

Step 1: Setup Your Drupal Commerce Site

We can install our Drupal demo site with the below-mentioned command. This provides us with a starter project and all the required products we need to get started with. If you are not familiar with how to set up the commerce site from scratch, visit the Commerce documentation(https://docs.drupalcommerce.org/commerce2) to know more about it. 

Once you are done installing the site. You need to do a few more things:

Step 2: Setup Your Gatsby Site

Here is a link to the starter project. Go through the readme file to check how to set up your Gatsby site. 

Let me walk you through the code and the flow:

Drupal Commerce with Gatsby

2. Gatsby-node.js: 

Drupal Commerce with Gatsby

By default, the gatsby-drupal-source plugin does not create product listing resources. If you visit your GraphQL endpoint you won’t find it. We are using OnCreateNode hook with some custom logic to create the allCommerceProduct listing resource at our GraphQL endpoint. 

Drupal Commerce with Gatsby

Here we are querying allProducts to create product pages dynamically by, passing the product id to our ProductDetail.js template. Then by using the context id in our template file we can query the product data for each product.

If you go to ProductDetail.js template file you can see how we are using the context id to query our product data.

The rest of the code is self-explanatory if you have worked with React before. 

Essentially these are the components that require your attention:

Drupal Commerce with Gatsby

Then we use it in our cart Component like this:

You can similarly modify your cart. Checkout Commerce API to learn more. You can integrate the user authentication functionality similarly. I have already written a blog post regarding this. Here is the link. 

This is all for now. Will come back with another blog post that will cover the payment integration. Till then see ya! 

P.S - Please mention your queries in the comments section. Happy to answer. 

We'd love to talk about your business objectives

Written by