Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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