Introduction to Gatsby + BigCommerce

Karen White
BigCommerce Developer Blog
10 min readSep 19, 2019

I first started experimenting with Gatsby about a year ago, during a time when it seemed like every podcast and blog in my feed was suddenly talking about the JAMstack. I hadn’t used a static site generator before, but I had some familiarity with React and a lot of curiosity about GraphQL. Setting up a Gatsby site seemed like a fun way to brush up on both technologies.

It didn’t take long to see why Gatsby has such an active community around it or to see the potential for using Gatsby alongside other platforms, like BigCommerce. For beginners like me, Gatsby has great documentation, and setting up a Gatsby site with Netlify makes it super easy to host the site and set up a continuous integration workflow.

While my Gatsby side projects are still in the experimental phase, I would like to share what I’ve learned so far. In this post, we’ll discuss some of the reasons why Gatsby is a great choice for decoupled ecommerce sites and break down the components of a Gatsby + BigCommerce integration.

For the record:

What this post is

My first impressions of working with Gatsby and a conceptual overview of how Gatsby fits into a headless strategy. We’ll talk high level architectures and lay out how Gatsby interacts with BigCommerce.

What this post is not

A step by step tutorial on building a Gatsby ecommerce site powered by BigCommerce. That’s out of scope for this post, but stay tuned — the BigCommerce team has been experimenting with Gatsby storefronts and we hope to have more Gatsby + BigCommerce content for you in the future.

Let’s dive in!

What is Gatsby?

If you called Gatsby a static site generator, you’d be correct, but it does more than output static HTML files. The front end is also a rehydrated React app, allowing you to manage state, call out to external web services, or authenticate users. There’s a perception that static site generators are only for building sites like documentation or marketing sites — use cases that are content focused, but not very dynamic. The rehydrated DOM allows you to build sites that are far more app-like, including ecommerce sites. Gatsby also works well with serverless function providers like Netlify Functions, for use cases like pinging a database or calling a server-to-server API, when you really do need a back end.

All that is to say that Gatsby brings the speed of a statically generated site as well as the functionality of a framework.

Gatsby also brings together technologies that will be familiar to modern web developers, in a bundle that’s easy to set up and configure, including React, webpack, and Babel. Tooling, including the CLI, is straightforward and dev-friendly.

But in my opinion, Gatsby’s real strength is the way it handles data sources. Gatsby introduces the concept of a “content mesh” to describe the way it links third-party platforms. The content mesh is a move away from all-in-one, monolithic platforms toward a model where each third-party platform is contributing a specialized functionality to the overall architecture — allowing each platform to do what it does best and the content mesh to bring it all together in a cohesive way.

Gatsby uses plugins to connect with third-party platforms and import data, which is exposed through a GraphQL layer. If you’re new to GraphQL, here’s a quick primer:

GraphQL is a query language for APIs. It allows you to structure your data request declaratively, meaning you can query the API for exactly the fields you want, and that’s the data that’s returned to you. As a developer, that makes GraphQL APIs really nice to work with because you can fetch just the data you need without having to traverse a response containing a bunch of extra properties. GraphQL queries can also encompass multiple resources in a single request, in contrast to a REST API where different resources would be separate endpoints. A GraphQL API essentially has a single endpoint that can query any of the data available to it.

So how does Gatsby use GraphQL? Any third-party data source that you connect via a plugin becomes available through the Gatsby GraphQL layer. You can visualize the Gatsby GraphQL layer through an Explorer interface accessible at mygatsbysite.com/___graphql. The Explorer allows you to see the full data graph, including resources from all connected data sources, and build and test GraphQL queries against the available data.

The Gatsby GraphQL data explorer

Once you’ve fine tuned your query to request the data you need, you can copy and paste the query directly into your React components, as in this example, which is pulling product data from my BigCommerce development sandbox store using the gatsby-source-bigcommerce plugin and displaying it in a table format:

product.js

import React from "react"
import { graphql } from "gatsby"
import Layout from "../components/layout"
export default ({ data }) => {
console.log(data)
return (
<Layout>
<div>
<h1>My Products</h1>
<table>
<thead>
<tr>
<th>Name</th>
<th>Description</th>
<th>Image</th>
<th>Price</th>
</tr>
</thead>
<tbody>
{data.allBigCommerceNode.edges.map(({ node }, index) => (
<tr key={index}>
<td>{node.name}</td>
<td><div dangerouslySetInnerHTML={{__html: node.description}}></div></td>
<td>
{node.images.map(({url_thumbnail}, index) =>(
<img key={index} src={url_thumbnail}/>
))}
</td>

<td>{node.price.toFixed(2)}</td>
</tr>
))}
</tbody>
</table>
</div>
</Layout>
)
}
export const query = graphql`
query {
allBigCommerceNode {
edges {
node {
images {
url_thumbnail
}
description
name
price
}
}
}
}
`

That’s a simple example, but the real power of the content mesh is the ability to create mashups using services sourced across multiple platforms. For instance, let’s say you want to build a site for a retail brand. The site will sell products, but the brand also has an extensive blog that brings a lot of visitors to the site. With Gatsby as a connector, you can use specialized ecommerce software like BigCommerce for the transactional parts of the site and specialized CMS software like Contenful to manage blog content.

What is Headless Ecommerce?

If the content mesh concept sounds familiar to readers of the BigCommerce Developer Blog, it might be because it’s so aligned with the headless direction we’ve been moving in over the last year. Headless commerce also trades monolithic, all-in-one solutions for a more modular and flexible approach.

Put simply, headless commerce decouples the front end, or head, of the ecommerce site from the ecommerce engine powering the back end. A headless ecommerce site using BigCommerce would use BigCommerce to manage products, orders, and cart creation, but a technology other than Stencil to render the presentation layer. The alternative presentation layer could be a custom React front end, a CMS like WordPress or Drupal — or Gatsby.

There are a few reasons why you might want to reach for a headless solution. One is the separation of concerns that’s addressed by the content mesh. If robust content management and ecommerce are both project requirements, it makes sense to look for technologies that do each of those things really well and merge them into a single solution. Another factor is the expertise of your engineering team. If your team is proficient in a particular stack, it can make sense to stick with a front end solution that really lets them flex their skills.

We’ve discussed some of the what and the why behind Gatsby and headless architectures, but let’s touch on the how. In the next section, we’ll break down what an integration between BigCommerce and Gatsby looks like.

BigCommerce + Gatsby

There are a few essential elements that make up a fully-functioning ecommerce site. You’ll need a way to:

  1. Display your products
  2. Add items to the cart
  3. Collect payment and complete the order

Each of these functions is supported by a different BigCommerce API: Catalog, Cart, and Checkout. From an architectural standpoint, we also have to think about where we want to manage products, customers, and orders. The most common approach is to manage all ecommerce concerns centrally from the BigCommerce dashboard, but sophisticated merchants might be managing customers through a CRM, products through a PIM, or orders through an ERP or OMS. Regardless of where staff log in to manage the store or which integrations are syncing data, product, order, and customer data will flow through the BigCommerce platform.

Importing Products

Let’s start with the most basic unit of an ecommerce store: the product. We’ll need a way to connect with the BigCommerce Catalog API to pull product data into Gatsby.

Gatsby plugins are Node packages that you can use to connect Gatsby to data sources or extend your site’s functionality. The Gatsby Plugin Library contains hundreds of community-contributed plugins. After installing a plugin package using npm or yarn, plugins are configured in the gatsby-config.js file.

You can use the gatsby-source-bigcommerce plugin from the Gatsby Plugin Library to connect to the BigCommerce API and specify the REST API endpoints whose data you want to pull into the Gatsby GraphQL layer. Here’s a sample config that creates GraphQL nodes for BigCommerce products and categories:

plugins: [
`gatsby-source-bigcommerce`,
{
resolve: 'gatsby-source-bigcommerce',
options: {
// REQUIRED
clientId: 'Your BigCommerce Client ID',
secret: 'Your BigCommerce Client Secret',
accessToken: 'Your BigCommerce API Token',
storeHash: 'Your BigCommerce store hash',
endpoints: {
BigCommerceProducts: "/catalog/products?include=images",
BigCommerceCategories: "/catalog/categories",
},

Once the product data has been pulled into Gatsby, you can use it in your React templates to create any presentation you wish. For example, you might want to create product detail pages programmatically from each BigCommerce product object.

Cart and Checkout

So we have products — that’s a great start. But chances are, you’re going to want a way for customers to buy those products. The BigCommerce server-to-server Cart API allows you to programmatically create and modify shopping carts from a remote server (i.e. a hosted web app or a serverless function). Using a serverless function service like Netlify Functions is a low overhead way to host a function that handles your add-to-cart functionality.

Here’s an example to show you what we mean. This POC was built by Nate Stewart, Head of Product Strategy at BigCommerce:

https://github.com/becomevocal/gatsby-starter-netlify-cms/blob/master/src/lambda/bigcommerce.js

This example uses the fastest and easiest method of resolving the checkout page securely — generating a redirect URL and redirecting to the checkout page on the BigCommerce domain. Once you’ve added at least one line item to the cart, you can use the /redirect_urls endpoint on the Cart API to generate a link that will take the shopper to the BigCommerce checkout page with their cart pre-loaded. The shopper will no longer be on the Gatsby site to complete the order, but this does offer a secure and lightweight solution for handling the checkout page.

BigCommerce also offers several other options for building checkout pages on remote storefronts: Embedded Checkout and the Server-to-Server Checkout API. Embedded Checkout is a version of the BigCommerce checkout that can be iframed into remote web pages. The Server-to-Server Checkout API is an extension of the Cart API that allows developers to build highly custom end-to-end checkouts on a remote platform. For a comparison of BigCommerce headless checkout options, see The Complete Guide to Checkout Customization on BigCommerce.

Multi-channel

Until now, we’ve been operating under the assumption of a 1:1 relationship between a BigCommerce store and a Gatsby site, with the BigCommerce store providing ecommerce functionality and the Gatsby site providing the connective data layer and front end. But that 1:1 relationship doesn’t necessarily need to be the case — a single BigCommerce store can provide backend ecommerce functionality for multiple Gatsby storefronts.

But, it’s a little more complicated than just piping product data to multiple Gatsby sites. At BigCommerce, we use the concept of channels to describe the catalog variations that a merchant manages across multiple outlets where they sell their products. A channel could be a marketplace, like Amazon, a headless storefront, or even a kiosk or mobile app. When multiple Gatsby sites are connected to a single BigCommerce store, we would consider each Gatsby site to be a separate channel. Each channel can have its own subset of products listed to it, with per-channel variations in price, name, and product description. The concept of channels is also important for sales attribution — it allows you to filter your store’s orders to track the number of orders placed on a per-channel basis.

We use the concepts of sites and routes to define the domain associated with each channel and the paths to important pages on the headless storefront, like the home page and the checkout page. The site and route URLs are used to ensure that links from invoice emails and the checkout page redirect back to the proper channel — an important consideration when managing multiple storefronts.

We’re still laying the groundwork for multi-storefront, headless scenarios, but Channels, Sites, and Routes APIs are in production today — most notably in the BigCommerce for WordPress plugin. Stay tuned for additional documentation in the BigCommerce Dev Center.

Conclusion

The verdict is in — at BigCommerce, we love Gatsby. We’re excited to continue experimenting with using Gatsby to build blazing fast ecommerce sites, so be sure to follow the BigCommerce Developer Blog for future tutorials and case studies.

Have you used Gatsby to build an ecommerce site, or used BigCommerce for a headless build? Show us what you’re working on and tell us what you learned by commenting below or tweeting @BigCommerceDevs.

--

--

Karen White
BigCommerce Developer Blog

Developer Marketing at Atlassian. Formerly at BigCommerce, Rasa. I think Voyager was the best Star Trek.