Adding to cart for headless stores

By default a headless store will only work once a Storefront Token has been added in PreProduct and the redirect has been set to “checkout”. This is because PreProduct doesn’t know your cart URL endpoint. However, this doc will explain how to set up add-to-cart for pre-orders.

If your store is not headless then the below process isn’t needed, you can simply toggle the front-end redirects in the PreProduct app. If your store is headless, then you’ll need to listen for the ppConvertingButtonClicked event, then stop PreProduct and make the needed API request instead. Here is an example of what the event listener might look like:

window.addEventListener('ppConvertingButtonClicked', (e) => {
   	e.detail.handled = true; // stop PreProduct requesting or redirecting

	addPreOrderToCart() // your custom function
}, false);

Below is an example of how you might make the API requests to Shopify using the Storefront API, you might prefer to make requests to your own server instead before making the request to Shopify. Either way, hopefully the below code is useful. (all of the PreProduct variables and functions are on the window object)

function addPreOrderToCart(){
	let url = `https://${ preproduct.shopify_domain }/api/${ PP_STOREFRONT_API_VERSION }/graphql.json`
		
	fetch(url, {
	  'async': true,
	  'crossDomain': true,
	  'method': 'POST',
	  'headers': {
		'X-Shopify-Storefront-Access-Token': {{ shopify storefront token goes here }},
		'Content-Type': 'application/graphql'
	  },
	  'body': CustomCreateCart()            // create the cart 
	  // 'body': CustomUpdateCart(cartId)	// or update an existing cart
	})
	.then(res => res.json())
	.then(parsedRes => {
		window.res = parsedRes;
		console.log(`see the response at window.res`);
	
	    setTimeout(() => {
  			// redirect or let the user know the carts been added too.
		})
	})	
}

function CustomCreateCart(){
  return `
	mutation {
	  cartCreate(
		input: {
			lines: [ ${ PPgraphqlLineItems() } ],
			note: ""
		  }
	  ) {
		  cart {
			id
			checkoutUrl
		  }
		  userErrors {
			field
			message
		  }
		}
	  }
  `
}

function CustomUpdateCart(cartId){
  return `
	mutation {
	  cartLinesAdd(
		  cartId: "${ cartId }", 
		  lines: [ ${ PPgraphqlLineItems() } ]
	  ) {
	  	cart {
	  		id
	  		checkoutUrl
			lines(first: 10) {
				edges {
				  node {
					id
					quantity
				  }
				}
		  	}
		}
		userErrors {
		  field
		  message
		}
	  }
	}
  `
}


window.addEventListener('ppConvertingButtonClicked', (e) => {
	e.detail.handled = true;
	addPreOrderToCart()
}, false);

Powered by BetterDocs

Pre-sell With PreProduct

7 day free trial with all plans