Discuss and resolve questions on Liquid, JavaScript, themes, sales channels, and site speed enhancements.
I can call Ajax API to add a product to cart then call below code to navigate users to the checkout page
const response = await fetch('/cart', {
headers: {
'content-type': 'application/x-www-form-urlencoded',
},
method: 'POST',
body: 'updates%5B%5D=1&updates%5B%5D=1&updates%5B%5D=1&checkout=',
});
location.href = response.url;
But I wondering if there is a better way since this code is quite tricky
Solved! Go to the solution
This is an accepted solution.
You can try this one. It will do the same based on the official cart API
// Function to add item to cart and redirect to checkout
async function cartToCheckout(variantId, quantity) {
try {
// Add item to cart
const addToCartResponse = await fetch('/cart/add.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
items: [{
id: variantId,
quantity: quantity
}]
})
});
if (!addToCartResponse.ok) {
throw new Error('Failed to add item to cart');
}
// Redirect to checkout
window.location.href = '/checkout';
} catch (error) {
console.error('Error:', error);
// Handle error (e.g., show error message to user)
}
}
// How to use
cartToCheckout(12345678, 1); // Replace 12345678 with actual variant ID
Do let me know if it works.
Thanks.
This is an accepted solution.
You can try this one. It will do the same based on the official cart API
// Function to add item to cart and redirect to checkout
async function cartToCheckout(variantId, quantity) {
try {
// Add item to cart
const addToCartResponse = await fetch('/cart/add.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
items: [{
id: variantId,
quantity: quantity
}]
})
});
if (!addToCartResponse.ok) {
throw new Error('Failed to add item to cart');
}
// Redirect to checkout
window.location.href = '/checkout';
} catch (error) {
console.error('Error:', error);
// Handle error (e.g., show error message to user)
}
}
// How to use
cartToCheckout(12345678, 1); // Replace 12345678 with actual variant ID
Do let me know if it works.
Thanks.
Thanks, dude! it works perfectly! I'm wondering why I wrote lines of very complicated code for just a line of "window.location.href = '/checkout'" 🤣
June brought summer energy to our community. Members jumped in with solutions, clicked ...
By JasonH Jun 5, 2025Learn how to build powerful custom workflows in Shopify Flow with expert guidance from ...
By Jacqui May 7, 2025Did You Know? May is named after Maia, the Roman goddess of growth and flourishing! ...
By JasonH May 2, 2025