Can I use the JavaScript Buy SDK or query/mutate with GraphQL from within the theme liquid files?

Solved

Can I use the JavaScript Buy SDK or query/mutate with GraphQL from within the theme liquid files?

Nortski
Shopify Partner
20 0 5

I'm trying to make my own private/custom app from my Admin area. At the moment I'm just testing whether I can return a list of products to the console. First I tried using the JS Buy SDK, I pasted this code in to the Product page template but it does not work:

// Build a custom products query using the unoptimized version of the SDK
const productsQuery = client.graphQLClient.query((root) => {
  root.addConnection('products', {args: {first: 10}}, (product) => {
    product.add('title');
    product.add('tags');// Add fields to be returned
  });
});

// Call the send method with the custom products query
client.graphQLClient.send(productsQuery).then(({model, data}) => {
  // Do something with the products
  console.log(model);
});

 

I've also tried querying the GraphQL:

const productQuery = () => `
  query {
    shop {
      products( first: 10) {
        edges{
          node {
            id
            handle
            title
	
            variants(first: 10){
              edges{
                node{
                  title
              }
            }
          }
        }
      }  
    }
  }
}
`;

const STOREFRONT_ACCESS_TOKEN =  'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
const GRAPHQL_URL = 'https://teststore.myshopify.com/api/2021-10/graphql.json'

const GRAPHQL_BODY  = () => {
	return {
	'async': true,
	'crossDomain': true,
	'method': 'POST',
	'headers': {
		'X-Shopify-Storefront-Access-Token': STOREFRONT_ACCESS_TOKEN,
		'Content-Type': 'application/graphql',
	},
	'body': productQuery()
	};
}

fetch(GRAPHQL_URL, GRAPHQL_BODY())
        .then(res => res.json())
	.then(products => {
		console.log('products', products)
	});

This also does not work. I get the following error:

Access to fetch at 'https://teststore.myshopify.com/api/2021-10/graphql.json' from origin 'https://teststore.myshopify.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Can someone please advise?

Accepted Solution (1)

HappyPoints
Shopify Partner
76 8 27

This is an accepted solution.

Hi @Nortski ,

 

You can try this code. It's working on my site.

 

 

const productQuery = `
  query {
      products( first: 10) {
        edges{
          node {
            id
            handle
            title
	
            variants(first: 10){
              edges{
                node{
                  title
              }
            }
          }
        }
      }  
    }
}
`;

const STOREFRONT_ACCESS_TOKEN =  'xxxxxxxxxxx'
const GRAPHQL_URL = '/api/2021-07/graphql.json'
  
fetch(GRAPHQL_URL, {
    method: "POST",
    headers: {
      'Content-Type': 'application/graphql',
      "X-Shopify-Storefront-Access-Token": STOREFRONT_ACCESS_TOKEN
    },
    body: productQuery
  })
  .then(res => res.json())
  .then(result => {
   
  });

 

 

Hope it helps.

HappyPoints | Shopify Expert in Store Development and Growth
If my reply is helpful and solved your question, please Mark It As Solution and Like to let me know!
Looking for a solution to increase sales? Install app DISCOS now!
Want to know who we are? Check out our website.

View solution in original post

Replies 6 (6)

HappyPoints
Shopify Partner
76 8 27

This is an accepted solution.

Hi @Nortski ,

 

You can try this code. It's working on my site.

 

 

const productQuery = `
  query {
      products( first: 10) {
        edges{
          node {
            id
            handle
            title
	
            variants(first: 10){
              edges{
                node{
                  title
              }
            }
          }
        }
      }  
    }
}
`;

const STOREFRONT_ACCESS_TOKEN =  'xxxxxxxxxxx'
const GRAPHQL_URL = '/api/2021-07/graphql.json'
  
fetch(GRAPHQL_URL, {
    method: "POST",
    headers: {
      'Content-Type': 'application/graphql',
      "X-Shopify-Storefront-Access-Token": STOREFRONT_ACCESS_TOKEN
    },
    body: productQuery
  })
  .then(res => res.json())
  .then(result => {
   
  });

 

 

Hope it helps.

HappyPoints | Shopify Expert in Store Development and Growth
If my reply is helpful and solved your question, please Mark It As Solution and Like to let me know!
Looking for a solution to increase sales? Install app DISCOS now!
Want to know who we are? Check out our website.
Nortski
Shopify Partner
20 0 5

Thank you, I will give it a try.

Nortski
Shopify Partner
20 0 5

Hmm it doesn't appear to do anything. But at least I'm not getting and error lol.

Nortski
Shopify Partner
20 0 5

No wait! It works, I forgot to dump the result to the console. Thanks 🙂

HappyPoints
Shopify Partner
76 8 27

 

@Nortski 

It's been my pleasure.

Best wishes for your business!

HappyPoints | Shopify Expert in Store Development and Growth
If my reply is helpful and solved your question, please Mark It As Solution and Like to let me know!
Looking for a solution to increase sales? Install app DISCOS now!
Want to know who we are? Check out our website.
greeshma
Shopify Partner
32 2 8

The {"errors":[{"message":"","extensions":{"code":"UNAUTHORIZED"}}]} error occurred. I added my app's API access token from the Shopify Partner account, so why did this happen? I am calling the query in the Theme Extension app's Liquid file, and then the error appeared.