Cart Cleanup After Checkout
This guide explains how to handle cart cleanup after successful checkout, including understanding cart persistence and implementing appropriate cleanup strategies.
Cart Persistence and Implications
In Elastic Path, carts persist even after an order has been created. This persistence has several implications to be aware of:
- Stale carts - Without cleanup, customers may return to carts with outdated items
- User experience - Customers could see previously purchased items still in their cart
Understanding cart persistence allows you to implement appropriate cleanup strategies that align with your business needs.
Cart Cleanup Options
Local Storage Cleanup
When using browser storage to track cart IDs, you should clear this storage after successful checkout:
// Clear cart ID from local storage
function clearLocalCart() {
// if you used a custom key on cart creation, use it here.
localStorage.removeItem("ep_cart_id");
}
API Cart Cleanup
The Elastic Path Shopper SDK provides methods to delete carts via the API:
import { deleteACart } from "@epcc-sdk/sdks-shopper";
// Delete a cart using the Shopper SDK
async function deleteCartFromAPI(cartId) {
try {
const response = await deleteACart({
path: {
cartID: cartId,
},
});
console.log("Cart successfully deleted");
return true;
} catch (error) {
console.error("Failed to delete cart:", error);
return false;
}
}
Comprehensive Cart Cleanup
For a complete cleanup solution, you could implement both local and API cleanup:
import { deleteACart } from "@epcc-sdk/sdks-shopper";
// Complete cart cleanup after successful checkout
async function cleanupAfterCheckout(cartId) {
// First try to delete the cart from the API
try {
await deleteACart({
path: {
cartID: cartId,
},
});
console.log("Cart successfully deleted from API");
} catch (error) {
console.error("Failed to delete cart from API:", error);
}
// Always clear local storage regardless of API success
localStorage.removeItem("ep_cart_id");
console.log("Local cart data cleared");
}