Skip to main content

Create & Retrieve a Cart

This guide explains how to create new shopping carts and retrieve existing ones in your Elastic Path implementation.

Using the initializeCart Utility​

The SDK provides a built-in initializeCart utility that simplifies cart creation and retrieval:

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

// Get or create a cart ID using the default storage key
const cartId = await initializeCart();

// Get cart ID without creating one (must use same storage key as initializeCart)
const existingCartId = getCartId();

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

// When retrieving a cart ID that was stored with a custom key,
// you must use the same custom key
const retrievedCartId = getCartId({
storageKey: "my-custom-cart-key",
});

How initializeCart Works​

The utility handles the entire cart initialization flow:

  1. Checks localStorage for an existing cart ID using the specified key (or default key)
  2. If a cart ID exists, returns it immediately
  3. If no cart ID exists, creates a new cart via the API
  4. Stores the new cart ID in localStorage with the specified key
  5. Returns the cart ID as a string

This approach is perfect for implementing guest checkout flows and ensuring the shopper always has an active cart.

Important Note on Storage Keys​

When using getCartId, you must provide the same storage key that was used with initializeCart:

  • If you called initializeCart() without a custom key, use getCartId() without a custom key
  • If you called initializeCart({ storageKey: "custom-key" }), you must use getCartId({ storageKey: "custom-key" })

Using different keys will result in getCartId returning null even if a cart exists.

Manual Cart Creation​

If you need more control over the cart creation process, you can use the manageCarts SDK method directly:

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

// Create a new cart
const response = await manageCarts({
path: {
cartID: "create",
},
body: {
data: {},
},
});

// Store the cart ID for later use
const cartId = response.data.data.id;
localStorage.setItem("ep_cart_id", cartId);

Configuration Options​

Key parameters when creating a cart:

  • Currency settings: Specify the currency for the cart
  • Store association: Associate the cart with a specific store
  • Customer association: Link the cart to an authenticated user

Extending Carts with Custom Data​

You can enhance carts with additional data to support custom business requirements. There are three ways to extend cart data:

1. Using Cart Meta Data​

Meta data allows you to attach custom key-value pairs to a cart:

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

// Get the current cart ID
const cartId = getCartId();

// Add meta data directly to the cart
const response = await manageCarts({
path: {
cartID: cartId,
},
body: {
data: {
meta: {
source: "mobile_app",
campaign_id: "summer_sale_2023",
utm_source: "email",
custom_notes: "Customer requested gift wrapping",
},
},
},
});

2. Creating Custom Cart Attributes​

For structured custom data, you can use custom attributes:

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

// Get the current cart ID
const cartId = getCartId();

// Add custom attributes directly to the cart
const response = await manageCarts({
path: {
cartID: cartId,
},
body: {
data: {
type: "cart",
id: cartId,
custom_attributes: {
delivery_instructions: "Leave at side door",
preferred_delivery_date: "2023-12-24",
gift_message: "Happy Birthday Mom!",
insurance_selected: true,
shipping_preferences: {
carrier: "fedex",
speed: "overnight",
},
},
},
},
});

3. Cart Flow Fields​

Cart flow fields let you store data for specific flow steps:

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

// Get the current cart ID
const cartId = getCartId();

// Add flow fields directly to the cart
const response = await manageCarts({
path: {
cartID: cartId,
},
body: {
data: {
type: "cart",
id: cartId,
flow: {
gift_options: {
gift_wrap: true,
gift_message: "Happy Birthday!",
gift_from: "Your Secret Admirer",
},
},
},
},
});

Best Practices for Extended Attributes​

  1. Use meaningful keys: Name attributes clearly to maintain code readability
  2. Keep it lightweight: Store only what you need - avoid excessive data
  3. Consider persistence: Some extended data may need to transfer to orders
  4. Be consistent: Use the same attribute structure across your application
  5. Validate input: Ensure attributes meet your schema requirements before storing

Retrieving an Existing Cart​

The getCart SDK method allows you to fetch an existing cart by its ID:

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

// Get cartId from localStorage using the same key used with initializeCart
const cartId = getCartId();

// Or with a custom storage key
// const cartId = getCartId({ storageKey: "my-custom-cart-key" });

// Retrieve the cart with items included
const response = await getCart({
path: {
cartID: cartId,
},
query: {
include: ["items"],
},
});

// Access the cart data
const cart = response.data;

Use Cases​

  • Retrieving carts after page refresh to maintain shopping state
  • Accessing saved carts for returning customers
  • Integrating with checkout flows to process orders
  • Retrieving cart information for display in mini-cart components

Integration with React Components​

Here's a concise pattern for integrating cart initialization in a React component:

import React, { useEffect, useState } from "react";
import { getCart, initializeCart } from "@epcc-sdk/sdks-shopper";

function CartComponent() {
const [cart, setCart] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);

// Optional: Use a custom storage key
const storageKey = "my-custom-cart-key";

useEffect(() => {
async function loadCart() {
try {
// Get or create cart ID (with optional custom storage key)
const cartId = await initializeCart({
storageKey, // Optional: Remove if using default key
});

// Fetch cart data
const response = await getCart({
path: { cartID: cartId },
query: { include: ["items"] },
});

setCart(response.data);
} catch (err) {
setError("Failed to initialize cart");
} finally {
setLoading(false);
}
}

loadCart();
}, []);

if (loading) return <p>Loading cart...</p>;
if (error) return <p>Error: {error}</p>;

return (
<div>
<h2>Your Cart</h2>
{/* Render cart details */}
</div>
);
}
tip

For a complete implementation example, check out the SPA Cart Example in the Elastic Path Composable Frontend repository.

Ask External AI