11 Essential Considerations When Implementing an Ecommerce Cart
Tags: opensource, webdev, javascript, programming
Published: 2023-03-07 13:10:49


Ecommerce cart functionality is essential for the success of an online store, as it is a way for customers to interact with the store and make their purchases. A properly designed cart can make the shopping experience simple, intuitive, and enjoyable, while a poorly designed cart can frustrate customers and lead to abandoned purchases.


The ecommerce cart plays several important roles in the online shopping process such as allowing customers to manage the products in their carts, display all total information, and more.


This article outlines the crucial aspects to consider for a successful ecommerce cart that satisfies both user needs and technical requirements.


> **What is Medusa?** [Medusa](https://medusajs.com/) is an open source set of ecommerce building blocks that aims to provide a flexible developer experience. Developers and business have full freedom in how they shape their ecommerce application, including how they can implement a cart. Learn how to get started with Medusa in [the documentation](https://docs.medusajs.com/usage/create-medusa-app).


## Cart User Experience Considerations


Are you aware that the average shopping [cart abandonment rate is 69.82%](https://baymard.com/lists/cart-abandonment-rate)? The journey doesn't end there despite a customer clicking “add to cart ” on your [product](https://medusajs.com/blog/what-i-learned-from-studying-500-b2b-ecommerce-sites/) page. Several new challenges come into play once a customer places a product into their shopping cart.


Remember that getting potential customers to add an item to their cart is just the starting point. It's an opportunity to convert that into a sale. One key factor in achieving this is the [user experience](https://medusajs.com/blog/9-best-ecommerce-ux-practices-with-examples/) of your ecommerce platform.


### Allow Users to Add, Remove and View Items in Their Cart


Customers should feel in control, so provide them with the option to delete items from their cart easily. However, you can also include a confirmation pop-up to ensure the action was intentional.


Make it simple for customers to edit items in their cart as well. For example, provide options to adjust the quantity with "+" or "-" buttons, a drop-down menu, or a box for manual entry. As demonstrated in the example below from the [Medusa Next.js](https://medusajs.com/blog/nextjs-ecommerce-storefront-comes-packed-with-ready-integrations-to-paypal-meilisearch-stripe-and-more/) storefront:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s7f7ce7qo3poepk80269.png)

Ensure that any modifications made to the cart are reflected in the product image and information. The goal is to keep the customer on the cart page and make the buying process seamless. Avoid redirecting customers back to the product page for any changes. The buying journey should be a progressive one.


### Be Upfront About Costs


To avoid losing customers, make sure the prices on your cart pages are clear and easy to understand. Hidden fees or unexpected costs can make customers feel tricked and discourage them from completing their purchase. 


[According to a study by the Baymard Institute, 55% of customers cited](https://baymard.com/blog/ecommerce-checkout-usability-report-and-benchmark) extra costs as the main reason for leaving their cart. To prevent this, clearly display taxes and shipping costs on their own line, along with the subtotal and total cost of the cart. 


If these costs vary by location, consider adding a tax, shipping calculator, and conversion rate to your page, so customers can see the costs before they checkout. A perfect example is the Medusa storefront sample used below, which shows the subtotal, shipping, and tax fee with the total cost. 


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sxtdfpb15ejp3oo5zjq4.png)


### Don’t Force Buyers to Create Accounts


Many customers abandon their shopping carts because creating an account on the website can take time and effort.[ In fact, 34% of people who took a survey by the Baymard Institute](https://www.drip.com/blog/cart-abandonment-statistics) cited this as a reason to abandon their shopping carts. To prevent this, offer a "guest checkout" option that allows customers to purchase without creating an account. This way, customers can easily complete a purchase, even if they only plan on buying something once and without any fuss.


### Offer Different Ways to Pay


Giving customers many options to pay will make it more likely for them to complete a purchase. If you don't offer a customer's preferred payment on your website, it may discourage them from finishing their purchase. Offering a limited number of payment options can limit customer choice and decrease the likelihood of a sale. You can start with the most popular payment methods, such as credit and debit cards, PayPal, and Google Pay, then you can expand from there.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6my9x84i52jdslj0apqb.png)

Source: Nike Checkout


### Simplify the Checkout Process 


Consolidating everything on a single page can improve customer experience and increase sales by eliminating multiple clicks and guesswork for shipping costs or account creation. Customers can see all necessary information on a single page, including payment processing, shipping details, and order information.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vy8jmm892phgyco02cau.png)


### Make Buying on Mobile Easy


Many people shop online using their phones. You could lose sales if your checkout process is not easy to use on the phone. Make sure your checkout page is set up for mobile users so they can easily complete their purchases.


### Abandoned Cart Recovery


There are several ways to recover abandoned carts, including sending reminder emails, offering incentives, and displaying abandoned items on the customer's next visit to the website. These methods can remind customers of the items left in their cart and encourage them to complete their purchases.


Offering special discounts or promotions for completing the purchase can also be effective. Another strategy is to track customer behavior, such as which items are frequently abandoned, and address any issues that may be causing customers to abandon their carts. 


From a technical perspective, you could implement a cron job that checks for newly created carts, if a cart is older than a specific amount of time, it would send an email to remind the customer of their cart and encourage them to complete their purchase.


Overall, abandoned cart recovery is an important aspect of ecommerce and can lead to significant increases in sales and revenue.


## Cart Technical Considerations


Important things to consider when you create and manage an online store include keeping customer data secure, data storage, website performance, and real-time updates.


### Security


Ensuring the security of customer information is paramount in an ecommerce site. When choosing a shopping cart solution, you must look for certifications and compliance measures to protect your customers from identity and information theft. 


Investing in a shopping cart solution with robust security credentials is crucial to maintaining the trust of your customers. Keeping your customer's information secure and following laws protecting their data is another important part of it. For instance, businesses operating in the EU must comply with the General Data Protection Regulation (GDPR). In the US, the Health Insurance Portability and Accountability Act (HIPAA) are mandatory regulation. 


These regulations mandate strict requirements for handling and protecting sensitive customer information.


### Sessions, Cookies, and Local Storage


Storing items in a cart between visits is crucial for an ecommerce website. One way to accomplish this is by using sessions, cookies, and local storage. Both are used to store information about the customer's cart on their browser. 


Sessions are saved on the website's computer and only last as long as the customer’s tab is opened on the browser. Another session is created if the customer opens another tab for the same site. Once the customer closes the tab, the session is destroyed. Cookies are saved on the customer's computer and can last even if the customer closes the tab or browser. Local storage is a type of web storage that allows web applications to store and access data on the client side (i.e., in the user's web browser) with no expiration.


This lets customers easily pick up where they left off and complete their purchase. Utilizing one of these options ensures customers a smooth and convenient shopping experience.


An example of using local storage is storing cart ID in local storage. The CartID is retrieved from the server stored in the browser's local storage.


```javascript
// Generate a unique cart ID
var cartId = "<value>";

// Store the cart ID in local storage
localStorage.setItem("cartId", cartId);
```


This code retrieves the cart information by retrieving the cartID stored in the local storage and then sends the cartID to make a request to the server, which fetches the cart details.


```javascript
const cartId = localStorage.getItem("cartId")
if (cartId){
	fetch(`/cart?cartId=${cartId}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    })
	.then((response) => response.json())
	.then(({ cart }) => {
		//display cart details
	})
}
```


This implementation above shows how cookies and local storage could be used together to manage a shopping cart. The cart ID is stored locally to allow the client to retrieve the cart information from the server.


### Real-Time Price Update


Updating the shopping cart and total price in real-time as the user makes changes is possible using JavaScript event listeners. For example, when a user clicks on the "add to cart" button, the JavaScript code will update the cart object and re-render the cart UI to reflect the change. 


Similarly, when a user changes the quantity of an item or removes an item from the cart, the JavaScript code will update the cart object and recalculate the total price. You can do this by assigning event listeners to the "add to cart", "remove from cart", and "quantity change" buttons.


Additionally, the total price displayed on the page should be updated to reflect the changes. This is just a basic example, you might need to follow extra steps to handle situations like trying to add an item that's unavailable yet or adding the same item more than once.


The site's performance must be considered, as recalculating the total price on every change may negatively affect the performance. Here is an example of how you might implement real-time updating of the cart and total price using JavaScript:


Note: This implementation focuses solely on client-side storage of the cart information. In a real-world scenario, communication with the server would be necessary to ensure the cart information is updated and accurate.


```bash
// Assign event listeners to the add to cart, remove from cart, and quantity change buttons
document.getElementById("add-to-cart-button").addEventListener("click", addToCart);
document.getElementById("remove-from-cart-button").addEventListener("click", removeFromCart);
document.getElementById("quantity-change-button").addEventListener("change", updateQuantity);

// Cart object to store the items in the cart
let cart = {};

// Function to add an item to the cart
function addToCart() {
    // Get item details from the page
    let item = {
        id: document.getElementById("item-id").value,
        name: document.getElementById("item-name").value,
        price: document.getElementById("item-price").value
    }
		// Call the calculate total price function
		calculateTotalPrice()

    // Add the item to the cart object
    cart[item.id] = item;

    // Re-render the cart UI to reflect the change
    renderCart();
}

// Function to remove an item from the cart
function removeFromCart() {
    // Get the id of the item to be removed
    let itemId = document.getElementById("item-id-to-remove").value;

    // Remove the item from the cart object
    delete cart[itemId];

    // Re-render the cart UI to reflect the change
    renderCart();

	// Call the calculate total price function
		calculateTotalPrice()

}

// Function to update the quantity of an item in the cart
function updateQuantity() {
    // Get the id of the item and the new quantity
    let itemId = document.getElementById("item-id-to-update").value;
    let newQuantity = document.getElementById("new-quantity").value;

    // Update the quantity in the cart object
    cart[itemId].quantity = newQuantity;

    // Re-calculate the total price
    let totalPrice = calculateTotalPrice();

    // Update the total price displayed on the page
    document.getElementById("total-price").innerHTML = totalPrice;
}

// Function to calculate the total price of the items in the cart
function calculateTotalPrice() {
    let totalPrice = 0;
    for (let itemId in cart) {
        totalPrice += cart[itemId].price * cart[itemId].quantity;
    }
    return totalPrice;
}

// Function to render the cart UI
function renderCart() {
    // Clear the existing cart UI
    document.getElementById("cart").innerHTML = "";

    // Iterate through the items in the cart and render them
    for (let itemId in cart) {
        let item = cart[itemId];
        let itemElement = document.createElement("div");
        itemElement.innerHTML = `<p>${item.name} - $${item.price} x ${item.quantity}</p>`;
        document.getElementById("cart").appendChild(itemElement);
    }
}
```


### Handling Out-of-Stock Items and Inventory Updates


When running an online store, it's essential to have a plan for handling things like items that are out of stock or inventory changes. A good way to handle items that are out of stock is to offer related or replacement items, for example, “Sorry, Nike Air Force 1 is out of stock, but we have the Nike Air Force 2 available.”


Another option is to show a message saying when the item will be back in stock and offer an option for customers to sign up for a mail notification to notify them when the item is available.


You can also let customers backorder items and ship them when they become available. Use inventory software to keep track of stock and update the website in real time. Also, let customers know when an item they're interested in is back in stock via email or a notification.


Limit the number of items a customer can purchase to the available stock and clearly communicate the item's status to customers so they can make informed decisions.


## Conclusion


In this article, we cover essential functionalities of an ecommerce cart from the user and technical standpoint, including responsiveness on mobile devices, access to various payment methods, offering guest accounts to new customers, handling out-of-stock items, real-time price updates, and saving the cart information in cookies.


Learn more about how to make a great online store with the Medusa quickstart guide [here](https://docs.medusajs.com/usage/create-medusa-app).


The documentation also provides two important guides related to carts:

- [How to implement a cart functionality](https://docs.medusajs.com/guides/carts-in-medusa)
- [How to implement checkout flow](https://docs.medusajs.com/advanced/storefront/how-to-implement-checkout-flow)

For any questions or support, you can reach the Medusa team through [Discord](https://discord.gg/medusajs).