3. API Request Utility Function Implementation
To send a GraphQL request to the Storefront API, you need correct HTTP headers, your store domain, and the Storefront Access Token. We will implement an asynchronous utility function for this.
3.1. Basic Configuration & Fetch Implementation
Using the fetch API, we write a reusable function that requests JSON data from the GraphQL endpoint.
// 1. Basic configuration of Shopify store
const SHOPIFY_DOMAIN = "example.myshopify.com"; // Replace with your actual store domain
const STOREFRONT_API_VERSION = "2026-01"; // Storefront API Version
const STOREFRONT_ACCESS_TOKEN = "00000000000000000000000000000000"; // Token issued in Step 1
// 2. Common GraphQL request utility function
async function storefrontRequest(query, variables = {}) {
const response = await fetch(
`https://${SHOPIFY_DOMAIN}/api/${STOREFRONT_API_VERSION}/graphql.json`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Shopify-Storefront-Access-Token": STOREFRONT_ACCESS_TOKEN,
},
body: JSON.stringify({ query, variables }),
}
);
const result = await response.json();
// Verify top-level errors
if (result.errors) {
console.error("GraphQL errors detected:", result.errors);
throw new Error("Storefront GraphQL error occurred.");
}
return result.data;
}