Liquid hack for a session/local storage alternative without Javascript
Sometimes, in a Shopify storefront, you want to show different content to a customer based on their behaviour or attributes.
Let me explain it by using these examples:
- You want to show gender specific product images based on the gender of a customer
- You want to create special layouts for a customer which birtdhday is the current day
- You want to save quiz data for a customer
99% of developers would say you can retrieve that information from the customer object (if the data was previously stored) or use local/session storage and update pages via JavaScript.
The problem?
This only works for logged-in customers!
When customers choose to remain anonymous/logged out while shopping, it's hard to know these things.
Also, session/local storage is not optimal because you must retrieve the information via JavaScript and then update the layout, which causes shifts.
The solution? Cart attributes 😎
"But wait, we do not want to save cart attributes? We want to save and use data about the current customer."
Exactly!
Cart attributes let you store data as key-value pairs for the current cart. Because the cart is a global object, we can use it to store data about the current session/customer. Let's call it a Liquid-based cookie 🍪
How does it work? You basically need two things.
1. Update the cart attributes with the Cart API on any action of your choice to save data
2. Use the 𝑐𝑎𝑟𝑡 object and its 𝑎𝑡𝑡𝑟𝑖𝑏𝑢𝑡𝑒𝑠 property in Liquid to read the data
Extra tip: Use Flow to attach the data to the actual customer after the order is created 😎
For a specific example, check out the slides!
By the way, this is not only good for adjusting your storefront. Having information about the current session is a game-changer in many aspects, so get creative.
𝘋𝘪𝘴𝘤𝘭𝘢𝘪𝘮𝘦𝘳: 𝘠𝘰𝘶 𝘯𝘦𝘦𝘥 𝘵𝘰 𝘣𝘦 𝘢𝘸𝘢𝘳𝘦 𝘰𝘧 𝘸𝘩𝘢𝘵 𝘥𝘢𝘵𝘢 𝘵𝘰 𝘴𝘢𝘷𝘦. 𝘛𝘩𝘪𝘴 𝘪𝘴 𝘫𝘶𝘴𝘵 𝘢 𝘴𝘩𝘰𝘸𝘤𝘢𝘴𝘦 𝘰𝘧 𝘸𝘩𝘢𝘵'𝘴 𝘱𝘰𝘴𝘴𝘪𝘣𝘭𝘦




