Skip to content

Instantly share code, notes, and snippets.

@kellyvaughn
Last active January 11, 2022 23:12
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kellyvaughn/b4ba8017367456166bd340dff99ca2a5 to your computer and use it in GitHub Desktop.
Save kellyvaughn/b4ba8017367456166bd340dff99ca2a5 to your computer and use it in GitHub Desktop.
Shopify GraphQL Storefront API using Vanilla JavaScript
// This example was used to pull in variant titles and IDs dynamically
// on a custom build of the ReCharge customer portal.
//
// Feel free to send me an email if you have any questions.
//
// Kelly Vaughn -- The Taproom Agency
// kelly@thetaproom.com
// 1. Retrieve product ID in any format
const productId = <pathToProductId>;
// 2. Define GraphQL input
const getVariantData = productId => `{
products(query:"id:${productId}" first:1 ) {
edges {
node {
variants(first:100) {
edges {
node {
title
id
}
}
}
}
}
}
}`;
// 3. Add component to render variants
const renderVariants = ({data}) => {
// fill in as needed
};
// 4. Define options
const options = {
method: "post",
headers: {
"Content-Type": "application/graphql",
"X-Shopify-Storefront-Access-Token": "<storefront-access-token>"
},
body: getVariantData(productId)
};
// 5. Fetch data
fetch(`https://<shop-name>.myshopify.com/api/graphql`, options)
.then(res => res.json())
.then(renderVariants);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment