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/cartAuthentication
Requires the x-api-key header for authentication.
Request
Headers
| Header | Type | Required | Description |
|---|---|---|---|
x-api-key | string | Yes | Your API authentication key |
Request Body
| Field | Type | Required | Description |
|---|---|---|---|
productId | string | Yes | The ID of the product to add |
quantity | number | Yes | Quantity 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 Code | Description |
|---|---|
401 | Invalid or missing API key |
409 | Product already in cart (use update endpoint instead) |
422 | Invalid input data (missing fields or invalid quantity) |
500 | Failed 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.
Related Endpoints
- Get Cart - View cart items
- Update Cart - Modify quantities
- Remove from Cart - Delete items