Add Snipcart To Gatsby

- 1 answer

I'm trying to integrate Snipcart into Gatsby (v2).

I edit the html.js file like this:

import React from "react"
import PropTypes from "prop-types"

export default class HTML extends React.Component {
  render() {
    return (
      <html {...this.props.htmlAttributes}>
          <meta charSet="utf-8" />
          <meta httpEquiv="x-ua-compatible" content="ie=edge" />
            content="width=device-width, initial-scale=1, shrink-to-fit=no"

          {/* Snipcart */}
          <script src=""></script>
          <script src="" id="snipcart" data-api-key="UF45pIjZjAtZWJkYS00MGEwLWIxZWEtNjljZThjNTRiNjA4NjM2NDg1MzAzMzQyNfDrr48"></script>
          <link target="_blank" rel="nofollow noreferrer" href="" type="text/css" rel="stylesheet" />

        <body {...this.props.bodyAttributes}>
            dangerouslySetInnerHTML={{ __html: this.props.body }}


HTML.propTypes = {
  htmlAttributes: PropTypes.object,
  headComponents: PropTypes.array,
  bodyAttributes: PropTypes.object,
  preBodyComponents: PropTypes.array,
  body: PropTypes.string,
  postBodyComponents: PropTypes.array,

What works:

If I create a div:

<a target="_blank" rel="nofollow noreferrer" href="#" class="snipcart-edit-profile">
   Edit profile

Snipcart works and opens the user profile when clicked.

What does not work:

When I want to use the public API, for example if I call:

Snipcart.api.user.logout() in a function.

=> error 'Snipcart' is not defined no-undef

How to have the global Snipcart object in all my app?



no-undef is a linter error and not a runtime one. So it doesn't indicate that Snipcart isn't available when your code run.

If it wasn't available, you would get this error in your browser's console: ReferenceError: Snipcart is not defined.

If you're using eslint, you can add a global variable like this in your eslint config:

    "globals": {
        "Snipcart": false

Alternatively, you can add a comment in the file where you use Snipcart's API: /* global Snipcart:false */

The Snipcart object will only be available in the browser so you should make sure not to call those functions while Gatsby is pre-rendering your website. That means you should only call Snipcart.api.* functions thought Gatsby's Browser API and not the SSR or Node APIs.

Also to make sure you're calling Snipcart's API only after its script is fully loaded, you can check the snipcart.ready event:

document.addEventListener('snipcart.ready', function() {
    // any Snipcart.api.* call