Re: How to Fetch Product Default Variant ID Using GraphQL in Shopify Theme App Extension

How to Fetch Product Default Variant ID Using GraphQL in Shopify Theme App Extension

greeshma
Shopify Partner
19 2 8

I am working on a Shopify Theme App Extension and trying to fetch the default variant ID of a product using GraphQL inside a Liquid file. I have the following GraphQL query:

const query = `
query {
product(id: "gid://shopify/Product/${productId}") {
variants(first: 1) {
edges {
node {
id
}
}
}
}
}
`;

I want to execute this query inside my Shopify Theme App Extension to retrieve the default variant ID of a product using its product ID.

However, I encountered an authentication error.

Could anyone guide me on how to correctly call this GraphQL query inside a Shopify Theme App Extension and fetch the data?

Replies 2 (2)

tansezer
Shopify Partner
11 0 1
query {
  productVariants(first: 1, query: "product_id:${productId}") {
    edges {
      node {
        id
      }
    }
  }
}
greeshma
Shopify Partner
19 2 8

async function getDefaultVariant(productId) {
const shopifyStore = "my-store.com";
const finalProductId = 'gid://shopify/Product/'+ productId;
const query = `
query {
product(id: "gid://shopify/Product/${productId}") {
variants(first: 1) {
edges {
node {
id
}
}
}
}
}
`;

const response = await fetch(`https://${shopifyStore}/admin/api/2023-10/graphql.json`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Shopify-Access-Token": 'app-access-token',
},
body: JSON.stringify({ query }),
});

const result = await response.json();
return result.data.product.variants.edges[0]?.node.id || null;
}

I am fetching the default variant ID of a product using the code below, but I am getting an authentication error. I am using this in a Theme App Extension Liquid file and obtaining the access token from my Shopify Partner account. Is the access token correct, or am I using the wrong one?