Skip to main content

Persist Cart Across Sessions

This guide explains how to maintain cart state when customers leave and return to your store.

Built-in Persistence with initializeCart

The Elastic Path SDK provides a built-in utility called initializeCart that handles cart persistence automatically:

import { initializeCart, getCartId } from "@epcc-sdk/sdks-shopper";

// Get or create a cart, automatically persisted in localStorage
const cartId = await initializeCart();

// Retrieve the cart ID without creating a new cart
const existingCartId = getCartId();

// Use custom storage key if needed
const cartIdWithCustomKey = await initializeCart({
storageKey: "my-custom-cart-key",
});

The initializeCart utility:

  1. Checks localStorage for an existing cart ID
  2. Returns it if found
  3. Creates a new cart via the API if not found
  4. Automatically stores the new cart ID in localStorage
  5. Returns the cart ID for immediate use

This is the recommended approach for most applications as it handles persistence seamlessly.

Custom Client-Side Storage Options

For more control or specific use cases, you may want to implement your own persistence strategy:

Using localStorage

A custom implementation using localStorage:

import { manageCarts } from "@epcc-sdk/sdks-shopper";

// Cart ID storage key
const CART_ID_KEY = "ep_cart_id";

// Create a cart and persist the ID
const createAndPersistCart = async () => {
// Create a new cart
const response = await manageCarts({
path: {
cartID: "create",
},
body: {
data: {},
},
});

const cartId = response.data.data.id;

// Store the cart ID in localStorage
localStorage.setItem(CART_ID_KEY, cartId);

return cartId;
};

// Get the persisted cart ID
const getCartId = () => {
return localStorage.getItem(CART_ID_KEY);
};

// Helper to check if we have a stored cart
const hasStoredCart = () => {
return !!getCartId();
};

// Remove the cart ID (e.g., after order completion)
const clearCartId = () => {
localStorage.removeItem(CART_ID_KEY);
};

Using Cookies

For multi-domain applications, cookies may be a better choice:

import { Cookies } from "react-cookie";
import { manageCarts } from "@epcc-sdk/sdks-shopper";

// Initialize cookies
const cookies = new Cookies();

// Cart ID cookie name
const CART_ID_COOKIE = "ep_cart_id";

// Create a cart and persist the ID in a cookie
const createAndPersistCart = async () => {
// Create a new cart
const response = await manageCarts({
path: {
cartID: "create",
},
body: {
data: {},
},
});

const cartId = response.data.data.id;

// Store the cart ID in a cookie (30 days expiration)
cookies.set(CART_ID_COOKIE, cartId, {
path: "/",
maxAge: 30 * 24 * 60 * 60, // 30 days in seconds
sameSite: "lax",
});

return cartId;
};

// Get the persisted cart ID
const getCartId = () => {
return cookies.get(CART_ID_COOKIE);
};

Comparison of Persistence Methods

MethodProsConsBest for
Built-in SDKSimplest implementation, handles edge casesLess customizableMost applications
localStorageLarger storage capacity, simpler APINot shared across domains, no expirationSingle-domain sites
CookiesWorks across subdomains, server accessibleSize limitations, included in requestsMulti-domain ecosystems

Security Considerations

  • Data minimization: Store only what's necessary (cart ID, not full cart data)
  • No sensitive information: Never store payment details or personal information
  • HTTPS only: Ensure your site uses HTTPS to protect stored data

Implementation for Different Platforms

  • React/Next.js: Use useState and useEffect hooks with localStorage
  • Server-Side Rendering: Access cookies on the server to maintain cart state
  • Mobile apps: Use AsyncStorage (React Native) or equivalent native storage
// Example React hook for cart persistence
function useCart() {
const [cartId, setCartId] = useState(() => {
// Initialize from localStorage (runs only on client)
if (typeof window !== "undefined") {
return localStorage.getItem(CART_ID_KEY) || null;
}
return null;
});

// Persist cart ID to localStorage when it changes
useEffect(() => {
if (cartId) {
localStorage.setItem(CART_ID_KEY, cartId);
} else {
localStorage.removeItem(CART_ID_KEY);
}
}, [cartId]);

return { cartId, setCartId };
}
tip

For a real-world implementation of cart persistence, see the SPA Cart Example on GitHub.