You visit a site.
Add products to cart.
Close the browser.
Come back after 3 days…
And BOOM 💥 your cart items are still there.
How?
Let’s break it down 👇
The naive answer: Session IDs
When you visit a website, the server assigns you a Session ID — a temporary identifier to track your activity. But here's the problem:
Session IDs are temporary. Close the browser, reopen it — new session, new ID. The cart is gone. That's not the experience users expect.
So how do production systems solve this?
The real solution: Persistent Guest Identity via Cookies + Server-Side Storage
Here's the architecture that actually works:
*Step 1 *— Generate a Persistent Guest ID
On your first visit, the frontend generates a UUID (e.g. crypto.randomUUID()) and stores it in a cookie with a long expiry (30–90 days). This ID persists across sessions, browser closes, and revisits.
Step 2 — Lazy Guest User Creation
When a guest adds a product to the cart, the backend receives that UUID and runs a simple check:
→ Does a guest user with this ID exist?
→ If NO → create a guest user record tied to this UUID
→ If YES → fetch that existing guest user
No login. No email. Just a UUID as the identity anchor.
Step 3 — Cart & Cart Items
Once the guest user is resolved:
→ Does this user have an active cart?
→ If NO → create a cart, add the item
→ If YES → append the new item to the existing cart
This means any number of products can be added across multiple visits — all seamlessly linked to that one UUID sitting quietly in the browser cookie.
Step 4 — Handling the Cookie Security Concerns
Storing sensitive cart data directly in cookies is risky (size limits, client-side tampering, XSS exposure). That's why we only store the UUID in the cookie — nothing else. All actual cart data lives safely on the server/database.
Step 5 — Cleanup with a Scheduled Job
Not every guest will ever check out. Over time, your database fills up with abandoned guest carts. The solution? A cron job / scheduler that runs periodically (daily or weekly) and:
→ Deletes guest users whose carts haven't been touched in X days (e.g. 30 days)
→ Cascades deletion to their cart and cart items
This keeps your database lean without manual intervention.
This small architectural decision improves:
✔️ User Experience
✔️ Conversion Rate
✔️ Abandoned Cart Recovery
✔️ Data Tracking
Sometimes the best engineering is invisible to users.
Top comments (0)