In e-commerce, creating a personalized shopping experience is crucial to retaining customers and increasing conversion rates. One way to achieve this is by showing customers their recently viewed products, allowing them to easily revisit products they may be interested in.
In this guide, we’ll walk through the process of implementing a “Recently Viewed Products” feature in Shopify using localStorage and some basic JavaScript. This approach ensures a lightweight solution that doesn’t require a complex back-end.
What You Will Learn:
- How to store recently viewed products in the user’s browser.
- How to display these products on any page.
- How to limit the number of products displayed and ensure only valid data is shown.
Why localStorage?
LocalStorage allows you to store data on the client side (the user’s browser). Since it’s persistent, the data remains even if the user navigates away from the page or closes their browser. This makes it perfect for tracking recently viewed products without needing back-end storage.
Step 1: Storing Recently Viewed Products in LocalStorage
To begin, we need to capture product data such as the title, image, price, and URL whenever a product page is viewed. This data will be stored in localStorage.
Here’s the Code:
// Store recently viewed product data in local storage
function setRecentlyViewedPdp() {
const pdpData = {
productTitle: "{{ product.title }}", // The title of the product
productImg: "{{ product.featured_image | img_url: '720x' }}", // The product image
productPrice: "{{ product.price | money }}", // The product price
productUrl: "{{ product.url }}", // The product URL
productHandle: "{{ product.handle }}" // The product handle (optional)
};
// Retrieve existing recently viewed products or start with an empty array
const productArr = JSON.parse(localStorage.getItem('recently_viewed')) || [];
const currPdpTitle = pdpData.productTitle;
const numberOfProducts = 4; // Maximum number of products to store
// Check if the product is already in recently viewed
if (!productArr.some(product => product.productTitle === currPdpTitle)) {
// If we already have 4 products, remove the oldest one
if (productArr.length >= numberOfProducts) {
productArr.shift();
}
// Add the current product to the array
productArr.push(pdpData);
// Save the updated array back to localStorage
localStorage.setItem('recently_viewed', JSON.stringify(productArr));
}
}
Key Points:
- localStorage stores data as strings, so we convert the product array to a string with
JSON.stringify
and convert it back to an array withJSON.parse
. - We ensure that no more than 4 products are stored by using
shift()
to remove the oldest item when the array reaches its limit.
Step 2: Displaying Recently Viewed Products
Next, we’ll retrieve the stored products from localStorage and display them on the site. We’ll limit the display to the last 4 products, ensuring only valid products with complete data are shown.
Code for Displaying the Products: