This project uses two WooCommerce APIs to interact with your store. Understanding how these APIs work is essential for building and maintaining the application.
Understanding WooCommerce APIs
This project uses two WooCommerce APIs for different purposes:
1. REST API (wc/v3)
- Purpose: Administrative operations
- Authentication: Consumer Key + Consumer Secret (OAuth 1.0a)
- Use Cases:
- Fetching product data
- Managing products/categories/tags (admin)
- Creating/updating orders
- User management
2. Store API (wc/store/v1)
- Purpose: Customer-facing operations
- Authentication: Cart Token (session-based)
- Use Cases:
- Adding items to cart
- Updating cart quantities
- Processing checkout
- Managing customer sessions
Key Difference: REST API is for admin operations (requires API keys), while Store API is for customer operations (uses session tokens).
WooCommerce Client Setup
The WooCommerce client is centralized in src/lib/woocommerce.js:
import WooCommerceRestApi from "@woocommerce/woocommerce-rest-api"; // Import WooCommerce REST API client
let wooClient = null; // Initialize WooCommerce client as null
export function getWooClient() { // Function to get WooCommerce client
if (!wooClient) {
wooClient = new WooCommerceRestApi({
url: process.env.WOO_BASE_URL, // Set WooCommerce base URL
consumerKey: process.env.WOO_CONSUMER_KEY,
consumerSecret: process.env.WOO_CONSUMER_SECRET, // Set WooCommerce consumer secret
version: process.env.WOO_VERSION || "wc/v3",
});
}
return wooClient; // Return WooCommerce client
}Singleton Pattern: The client uses a singleton pattern to ensure only one instance is created, improving performance and reducing memory usage.
WooCommerceAPI Service
The project provides a service layer (WooCommerceAPI) with helper methods for common operations:
Products API Methods
Get Products with Pagination
// Get products with pagination and filters
const result = await WooCommerceAPI.getProducts({
page: 1,
per_page: 12,
category: 15,
search: "laptop",
orderby: "price",
order: "asc"
});
// Returns:
// {
// products: [...],
// totalPages: 10,
// total: 120
// }Get Single Product by Slug
// Get a single product by its slug
const product = await WooCommerceAPI.getProductBySlug("laptop-pro");
// Returns product object or null if not found
if (product) {
console.log(product.name, product.price);
}Search Products
// Search products by keyword
const results = await WooCommerceAPI.searchProducts("laptop", {
per_page: 20,
category: 15
});
// Returns products matching the search termGet Products by Price Range
// Get products within a price range
const products = await WooCommerceAPI.getProductsByPriceRange(100, 500, {
per_page: 12
});
// Returns products with price between $100 and $500Get Products by IDs
// Get specific products by their IDs
const products = await WooCommerceAPI.getProductsByIds([1, 2, 3, 4, 5]);
// Useful for wishlist, recently viewed, etc.Get Product Variations
// Get all variations for a variable product
const variations = await WooCommerceAPI.getProductVariations(productId);
// Returns array of variation objects with attributes and pricesCategories API Methods
// Get all categories
const categories = await WooCommerceAPI.getCategories();
// Get category by slug
const category = await WooCommerceAPI.getCategoryBySlug("electronics");
// Get subcategories
const subcategories = await WooCommerceAPI.getSubcategories(parentId);
// Get category with products
const data = await WooCommerceAPI.getCategoryWithProducts("electronics");Store API Integration
For cart and checkout operations, the project uses WooCommerce Store API directly:
Cart Token Management
The Store API uses a Cart Token for session management:
// Cart token is stored in cookies
// Format: cart_token=abc123xyz
// Extracting cart token from cookies
function getCartTokenFromCookie(cookieHeader) {
if (!cookieHeader) return "";
const match = /(?:^|; )cart_token=([^;]+)/i.exec(cookieHeader);
if (!match) return "";
try {
return decodeURIComponent(match[1]);
} catch {
return match[1];
}
}How Cart Tokens Work
- Generated automatically by WooCommerce on first cart operation
- Stored in httpOnly cookies for security
- Sent with every cart/checkout request
- Persists across page refreshes and browser sessions
- Expires after a period of inactivity (configurable in WooCommerce)
Store API Endpoints Used
| Method | Endpoint | Purpose |
|---|---|---|
|
|
Get current cart contents |
|
|
Add item to cart |
|
|
Update cart item quantity |
|
|
Remove item from cart |
|
|
Get checkout data (shipping rates, payment methods) |
|
|
Update checkout information (addresses, shipping) |
|
|
Process order and payment |
Making Direct API Calls
While the service layer provides convenience methods, you can also make direct API calls:
Using REST API Directly
import { getWooClient } from "@/lib/woocommerce";
// Get the WooCommerce client
const api = getWooClient();
// Make a direct API call
const response = await api.get("products", {
per_page: 10,
status: "publish"
});
// Access the data
const products = response.data;
const totalPages = response.headers["x-wp-totalpages"];
const total = response.headers["x-wp-total"];Using Store API Directly
// Get cart token from cookies
const cartToken = getCartTokenFromCookie(request.headers.get("cookie"));
// Make Store API call
const response = await fetch(
`${baseUrl}/wp-json/wc/store/v1/cart`,
{
method: "GET",
headers: {
"User-Agent": "woocommerce-next-proxy",
"Cart-Token": cartToken
}
}
);
const cartData = await response.json();Error Handling
Always handle errors when making API calls:
try {
const result = await WooCommerceAPI.getProducts();
// Use result
} catch (error) {
if (error.response) {
// API responded with error status
console.error("API Error:", error.response.data);
console.error("Status:", error.response.status);
} else if (error.request) {
// Request made but no response
console.error("Network Error:", error.message);
} else {
// Something else happened
console.error("Error:", error.message);
}
}Rate Limiting
Important: WooCommerce APIs may have rate limits. Implement caching and request batching when possible to avoid hitting limits.
Best Practices
- Use Service Layer: Prefer using
WooCommerceAPImethods over direct API calls - Cache Responses: Cache product and category data when appropriate
- Handle Errors: Always wrap API calls in try-catch blocks
- Validate Data: Validate API responses before using them
- Use Environment Variables: Never hardcode API credentials
Next Steps: Learn about Next.js Frontend patterns and API Routes implementation.