Retrieving data from Shopify GraphQL API

Hello!

Our team implemented a feature to retrieve product metafields using Shopify’s GraphQL Admin API, with the requests being made directly from the front end (client-side). This approach initially worked without any issues.

However, we recently started encountering CORS errors with these requests. After consulting a Shopify Advisor, we were informed that accessing metafields via the Admin API from the front end is not supported and that server-side solutions are recommended for such use cases.

We are now trying to understand why this issue did not occur before and why the CORS error started appearing only recently. Have there been any recent updates to Shopify’s CORS policy that could explain this change? If so, could you point me to any documentation or release notes regarding this?

Hi @Mariia_Tanchuk

I assume you mean your app was making frontend requests to the Admin API directly, not standalone JavaScript running on a storefront website.

Either way, I’m not sure how you were able to run these requests for so long without running into CORS security issues. It’s also a security issue to leak the merchant’s offline access token to the frontend of your app or public website.

You should really protect that API key by keeping it on the server side of your application. It’s just the best practice.

Then you can use the Session Token issued by Shopify on the frontend to make authenticated API calls to your backend. For example, I have an API route in one of my apps that simply proxies these GraphQL calls directly to the Admin API after the session token from the request from the frontend has been verified.

Hope this helps, I wouldn’t focus on the CORS error too much.

I dont know of any CORS policy changes, but you’ve never been able to request data with the Admin API directly from the storefront.

You have the Storefront API where product metafield data is available: product - Storefront API

Could look something like this

const query = `
  {
    product(id: 'gid://shopify/Product/${ID}') {
      metafield(namespace: 'namespace', key: 'key') {
        value
        type
      }
    }
  }
`;

const response = await fetch('/api/2024-10/graphql.json', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-Shopify-Storefront-Access-Token': 'YOUR_PUBLIC_KEY'
  },
  body: JSON.stringify({ query })
});

const { data } = await response.json();    

Just be aware that anyone can see and use your public API key. However, for most merchants it’s not really a problem, as it has only access to public data. But it’s worth to consider.

1 Like