use-shopping-cart logouse-shopping-cart
Examples

Metadata Example

Using product_metadata and price_metadata to attach custom data to cart entries.

Where Metadata Goes

addItem takes two kinds of metadata, and they end up in different places:

OptionStored on the cart entry asSent to Stripe by validateCartItems
product_metadataproduct_data.metadataYes, as the line item's price_data.product_data.metadata
price_metadataprice_data.metadataNo

Stripe Checkout creates a new Product for each inline line item, and that Product keeps product_data.metadata. Inline prices can't carry metadata, so price_metadata stays in the cart. Use it for data your own UI or server reads, and put anything you need in Stripe or in webhooks in product_metadata.

Adding the same product again merges the new metadata into the existing entry. Give each variant its own product id so their metadata stays separate.

Basic Usage

import { useShoppingCart } from 'use-shopping-cart'

function ProductWithMetadata() {
  const { addItem } = useShoppingCart()

  const product = {
    id: 'tshirt_blk_m',
    name: 'T-Shirt (Black, M)',
    price: 2000,
    currency: 'USD',
    image: 'https://example.com/tshirt.jpg'
  }

  const handleAddToCart = () => {
    addItem(product, {
      product_metadata: {
        size: 'M',
        color: 'Black',
        variant_sku: 'TSHIRT-BLK-M'
      },
      price_metadata: {
        badge: 'summer-sale'
      }
    })
  }

  return <button onClick={handleAddToCart}>Add to Cart</button>
}

Read it back from the cart entry:

const { cartDetails } = useShoppingCart()
const entry = cartDetails.tshirt_blk_m

entry.product_data.metadata.variant_sku
entry.price_data.metadata.badge

Custom Engraving

function PersonalizedProduct({ product }) {
  const { addItem } = useShoppingCart()
  const [engraving, setEngraving] = useState('')

  const handleAddToCart = () => {
    addItem(product, {
      product_metadata: { engraving_text: engraving }
    })
  }

  return (
    <div>
      <input
        type="text"
        value={engraving}
        onChange={(e) => setEngraving(e.target.value)}
        placeholder="Engraving text (optional)"
        maxLength={20}
      />
      <button onClick={handleAddToCart}>Add to Cart</button>
    </div>
  )
}

If engraving costs extra, sell it as its own product in the inventory (for example engraving_fee) and add it to the cart. Don't change price in the browser: validateCartItems charges the price from your inventory.

Server-Side Access

In Checkout Session Creation

validateCartItems takes prices, names and price_data from your inventory. From the cart it keeps only each cart entry's quantity and product_data.metadata, and the cart's metadata can't overwrite keys set in your inventory's product_data.metadata:

// pages/api/create-checkout-session.js
import Stripe from 'stripe'
import { validateCartItems } from 'use-shopping-cart/utilities'
import { inventory } from '../../data/products'

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY)

export default async function handler(req, res) {
  try {
    const { cartDetails } = req.body
    const line_items = validateCartItems(inventory, cartDetails)

    const session = await stripe.checkout.sessions.create({
      mode: 'payment',
      line_items,
      success_url: `${req.headers.origin}/success?session_id={CHECKOUT_SESSION_ID}`,
      cancel_url: req.headers.origin,
      metadata: {
        order_type: 'web',
        source: 'shopping-cart'
      }
    })

    res.redirect(303, session.url)
  } catch (error) {
    res.status(500).json({ error: error.message })
  }
}

Metadata comes from the browser, so treat it as customer input: fine for an engraving message or a size, not for anything that decides what you charge or ship without checking it. Put data you rely on, such as a fulfillment SKU, in your inventory's product_data.metadata: its keys win over the cart's.

In Webhooks

// pages/api/webhooks/stripe.js
import Stripe from 'stripe'
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY)

export default async function handler(req, res) {
  const sig = req.headers['stripe-signature']
  let event

  try {
    event = stripe.webhooks.constructEvent(
      req.body,
      sig,
      process.env.STRIPE_WEBHOOK_SECRET
    )
  } catch (err) {
    return res.status(400).send(`Webhook Error: ${err.message}`)
  }

  if (event.type === 'checkout.session.completed') {
    const session = await stripe.checkout.sessions.retrieve(
      event.data.object.id,
      { expand: ['line_items.data.price.product'] }
    )

    for (const lineItem of session.line_items.data) {
      const metadata = lineItem.price.product.metadata

      if (metadata.engraving_text) {
        await createEngravingOrder({
          text: metadata.engraving_text,
          quantity: lineItem.quantity
        })
      }
    }
  }

  res.json({ received: true })
}

Best Practices

Use Strings

Stripe stores metadata values as strings, so send strings:

product_metadata: {
  size: 'Medium',
  is_gift: 'true',
  weight_kg: '2.5'
}

Stay Within Stripe's Limits

Stripe allows up to 50 keys per object, 40 characters per key and 500 characters per value.

Use Clear Names

product_metadata: {
  category: 'electronics',
  model: 'X1000'
}

On this page

Shopping Cart

Your cart is empty

Try the interactive demos on the docs pages!