Event

liquid-ajax-cart:request-start

The liquid-ajax-cart:request-start event is fired at the document a moment before a Shopify Cart API Ajax request is performed. You can read, modify or cancel the request.

Structure

The event’s detail property contains a Request state object of the current Shopify Cart API Ajax request.

Since the event is fired before the request is performed, the Request state object won’t have the responseData, extraResponseData and fetchError properties:

document.addEventListener("liquid-ajax-cart:request-start", function(event) {
  const {requestState} = event.detail;

  // Print the requestState before the request is performed
  console.log(requestState);
});

Result:

{
  "endpoint": "/cart/add.js",
  "requestBody": {…},
  "requestType": "add",
  "info": {…}
}

The requestState.requestBody and requestState.info are objects you can mutate to change the request.

Mutate a request

The requestState.requestBody and requestState.info properties are references to the objects that will be used in the request. So you can mutate the objects if you want to change the request before it is performed. But if you assign a new object to the requestState.requestBody and requestState.info properties it won’t work:

Correct

document.addEventListener("liquid-ajax-cart:request-start", function(event) {
  const {requestState} = event.detail;
  if (requestState.requestType === 'change') {
    if (requestState.requestBody instanceof FormData || requestState.requestBody instanceof URLSearchParams) {
      // Mutating the "requestBody" object is allowed
      requestState.requestBody.set('quantity', 2);
    } else {
      // Mutating the "requestBody" object is allowed
      requestState.requestBody.quantity = 2;
    }
  }

  // Mutating the "requestBody" object is allowed
  requestState.info.myCustomData = 'value';
});

Wrong

document.addEventListener("liquid-ajax-cart:request-start", function(event) {
  const {requestState} = event.detail;
  if (requestState.requestType === 'change') {
    // Assigning another object to the "requestBody" won't work
    requestState.requestBody = newRequestObject;
  }

  // Assigning another object to the "info" won't work
  requestState.info = {myCustomData: 'value'};
});

Cancel a request

You can cancel the request by mutating the requestState.info object and setting the requestState.info.cancel to true. The request won’t be performed but the liquid-ajax-cart:request-end event will be fired anyway.

document.addEventListener("liquid-ajax-cart:request-start", function(event) {
  const {requestState} = event.detail;

  // Cancel the request
  requestState.info.cancel = true;
})