Hi everyone. I was hoping someone can point me in the correct direction. I’m trying to add a variant to a product when adding to cart, which gives it a unique price. This calls my server and then calls Shopify API. Now where I’m at works great, but the issue I’m having is it takes a good 15–30 seconds for this product to appear in the basket. The weird thing is, if I send the customer to check out instantly, the product is there with price and an image. Is there any way I can make the basket any faster ? Here’s my code :
The HTML ( product ID as been replaced)
<form id="customPriceForm">
<input type="hidden" id="productId" name="productId" value="1231231231231">
<input type="number" id="customPrice" name="customPrice" placeholder="Enter Your Price" step="0.01" required>
<button type="submit">Create Variant and Add to Cart</button>
</form>
<script src="{{ 'TESTjava.js' | asset_url }}"></script>
Client side JavaScript
document.getElementById('customPriceForm').addEventListener('submit', async function(event) {
event.preventDefault();
try {
const productId = document.getElementById('productId').value;
const customPrice = document.getElementById('customPrice').value;
// Show loading indicator to the user here
console.log('Processing...');
const createVariantResponse = await fetch('https://**MYSERVER**/create-dynamic-variant', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ productId, customPrice })
});
if (!createVariantResponse.ok) {
throw new Error('Network response was not ok when creating variant');
}
const data = await createVariantResponse.json();
if (!data.success || !data.variantId) {
throw new Error('Failed to create variant.');
}
console.log('Variant created:', data);
const cartResponse = await fetch('/cart/add.js', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
id: data.variantId,
quantity: 1
})
});
if (!cartResponse.ok) {
throw new Error('Network response was not ok when adding to cart');
}
const cartData = await cartResponse.json();
console.log('Variant added to cart:', cartData);
window.location.href = '/checkout'; // Redirect to cart when the price is correct
} catch (error) {
console.error('Error:', error);
// Handle errors (e.g., show message to user)
// Hide loading indicator here if shown
}
});
Server side :
app.post('/create-dynamic-variant', async (req, res) => {
const { productId, customPrice } = req.body;
// Validate input to ensure required parameters are present
if (!productId || !customPrice) {
return res.status(400).json({
success: false,
message: 'Missing required parameters: productId and customPrice.'
});
}
try {
// It's efficient to keep try-catch blocks as small as possible
const product = await shopify.product.get(productId);
const variantTitle = "CG#" + Math.random().toString(36).substring(7); // Simplified variantTitle generation
const newVariant = await createVariant(productId, variantTitle, customPrice);
// If newVariant is not created, throw an error
if (!newVariant) {
throw new Error('Variant creation failed');
}
console.log(`Variant created successfully: ID ${newVariant.id}, Title "${newVariant.title}", Price ${newVariant.price}`);
res.status(200).json({ success: true, variantId: newVariant.id, message: 'Variant created successfully.' });
} catch (error) {
console.error('Error creating dynamic variant:', error.message || 'Unknown error');
res.status(500).json({
success: false,
message: 'Error creating dynamic variant.',
errorDetail: error.message || 'Unknown error'
});
}
});
// Refactored variant creation into a separate function for clarity and reusability
async function createVariant(productId, variantTitle, customPrice) {
return shopify.productVariant.create(productId, {
title: variantTitle,
price: customPrice,
inventory_management: null, // Indicates not to track inventory for this variant
inventory_policy: 'deny',
option1: variantTitle, // Setting option1 to the dynamically generated variant title
});
}
Any help or method to make it quicker would be much appreciated :).
Thank you !