WooCommerce Integration

Updated 8 July 2026

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)
2. Store API (wc/store/v1)

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 term

Get 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 $500

Get 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 prices

Categories 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

Store API Endpoints Used

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