My App
Cart

Add to Cart

Add a product to the shopping cart

Overview

Add a product to the shopping cart with a specified quantity. This endpoint supports both authenticated and guest users, automatically managing cart persistence.

Endpoint

POST /v1/cart

Authentication

Requires the x-api-key header for authentication.

Request

Headers

HeaderTypeRequiredDescription
x-api-keystringYesYour API authentication key

Request Body

FieldTypeRequiredDescription
productIdstringYesThe ID of the product to add
quantitynumberYesQuantity to add (minimum: 1)

Example Request

async function addToCart(productId, quantity) {
  const response = await fetch('https://api.yourstore.com/v1/cart', {
    method: 'POST',
    headers: {
      'x-api-key': process.env.BACKEND_API_KEY,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      productId,
      quantity
    })
  });

  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.message || 'Failed to add to cart');
  }

  const guestToken = response.headers.get('x-guest-token');
  if (guestToken) {
    localStorage.setItem('guest_token', guestToken);
  }

  return response.json();
}

// Usage
addToCart('prod_123', 2)
  .then(cart => console.log('Added to cart:', cart))
  .catch(error => console.error(error));
interface AddToCartRequest {
  productId: string;
  quantity: number;
}

interface CartResponse {
  id: string;
  productId: string;
  quantity: number;
  price: number;
}

async function addToCart(
  productId: string, 
  quantity: number
): Promise<CartResponse[]> {
  const response = await fetch('https://api.yourstore.com/v1/cart', {
    method: 'POST',
    headers: {
      'x-api-key': process.env.BACKEND_API_KEY!,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      productId,
      quantity
    } as AddToCartRequest)
  });

  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.message || 'Failed to add to cart');
  }

  const guestToken = response.headers.get('x-guest-token');
  if (guestToken) {
    localStorage.setItem('guest_token', guestToken);
  }

  return response.json();
}

Server Action Example (Next.js)

'use server';

import { cookieManager } from '@/lib/auth-tools';
import { revalidatePath } from 'next/cache';

export async function addToCartAction(productId, quantity) {
  try {
    const headers = await cookieManager.buildApiHeaders();
    
    const response = await fetch('https://api.yourstore.com/v1/cart', {
      method: 'POST',
      headers,
      body: JSON.stringify({ productId, quantity })
    });

    if (!response.ok) {
      const error = await response.json();
      return { 
        success: false, 
        message: error.message 
      };
    }

    await cookieManager.handleApiResponse(response);
    const cart = await response.json();
    
    revalidatePath('/cart');
    
    return { 
      success: true, 
      cart 
    };
  } catch (error) {
    return { 
      success: false, 
      message: 'Failed to add to cart' 
    };
  }
}
'use server';

import { cookieManager } from '@/lib/auth-tools';
import { revalidatePath } from 'next/cache';

interface AddToCartResult {
  success: boolean;
  cart?: any[];
  message?: string;
}

export async function addToCartAction(
  productId: string, 
  quantity: number
): Promise<AddToCartResult> {
  try {
    const headers = await cookieManager.buildApiHeaders();
    
    const response = await fetch('https://api.yourstore.com/v1/cart', {
      method: 'POST',
      headers,
      body: JSON.stringify({ productId, quantity })
    });

    if (!response.ok) {
      const error = await response.json();
      return { 
        success: false, 
        message: error.message 
      };
    }

    await cookieManager.handleApiResponse(response);
    const cart = await response.json();
    
    revalidatePath('/cart');
    
    return { 
      success: true, 
      cart 
    };
  } catch (error) {
    return { 
      success: false, 
      message: 'Failed to add to cart' 
    };
  }
}

Client Component Usage

'use client';

import { addToCartAction } from '@/actions/cart';
import { useState } from 'react';

export function AddToCartButton({ productId }) {
  const [loading, setLoading] = useState(false);

  const handleAddToCart = async () => {
    setLoading(true);
    const result = await addToCartAction(productId, 1);
    
    if (result.success) {
      alert('Added to cart!');
    } else {
      alert(result.message);
    }
    setLoading(false);
  };

  return (
    <button onClick={handleAddToCart} disabled={loading}>
      {loading ? 'Adding...' : 'Add to Cart'}
    </button>
  );
}

Response

Success Response (200)

Returns the updated cart items array.

[
  {
    "id": "cart_123",
    "productId": "prod_456",
    "quantity": 2,
    "price": 29.99,
    "product": {
      "name": "Wireless Headphones",
      "image": "https://example.com/images/headphones.jpg"
    }
  }
]

Error Responses

Status CodeDescription
401Invalid or missing API key
409Product already in cart (use update endpoint instead)
422Invalid input data (missing fields or invalid quantity)
500Failed to add item to cart

Important Notes

Duplicate Products: If a product already exists in the cart, you'll receive a 409 error. Use the Update Cart endpoint to modify quantities of existing items.

Stock Validation: The API automatically validates product availability and stock levels before adding to cart.

Common Use Cases

Product Page

Add a single product to cart from the product detail page with user-selected quantity.

Quick Add

Implement quick-add buttons on product listing pages for one-click additions.

Bundle Products

Add multiple related products sequentially when creating product bundles.