Sync external products into WooCommerce with the REST API. Covers batch upsert patterns, variable products, inventory reconciliation, and sync scheduling. This practical guide covers step-by-step setup, real-world code snippets, security hardening, and common production edge cases.
Introduction
If you manage a WooCommerce store alongside a third-party system — an ERP, a supplier's catalogue, a POS, or a custom inventory database — you'll eventually need to synchronise products between them. Manually exporting and importing CSV files doesn't scale; the WooCommerce REST API does.
This guide builds a complete, production-ready product sync system in Node.js/TypeScript that:
- Checks whether a product exists before creating or updating it
- Uses batch API calls to minimise requests
- Handles simple and variable products with variations
- Syncs product images from external URLs
- Runs on a schedule and logs errors gracefully
Prerequisites
- WooCommerce store with REST API keys (Consumer Key + Consumer Secret)
- Node.js 18+ with TypeScript
@woocommerce/woocommerce-rest-apipackage
1. Project Setup
mkdir woo-product-sync && cd woo-product-sync
npm init -y
npm install @woocommerce/woocommerce-rest-api typescript tsx dotenv
npx tsc --init
Create .env:
WOO_URL=https://yourstore.com
WOO_CONSUMER_KEY=ck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
WOO_CONSUMER_SECRET=cs_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Create the API client:
// src/client.ts
import WooCommerceRestApi from '@woocommerce/woocommerce-rest-api';
import 'dotenv/config';
export const woo = new WooCommerceRestApi({
url: process.env.WOO_URL!,
consumerKey: process.env.WOO_CONSUMER_KEY!,
consumerSecret: process.env.WOO_CONSUMER_SECRET!,
version: 'wc/v3',
});
2. Define Your External Product Shape
Imagine your external system exports products like this:
// src/types.ts
export interface ExternalProduct {
sku: string;
name: string;
description: string;
shortDescription: string;
price: number;
salePrice?: number;
stockQuantity: number;
categories: string[]; // category names
imageUrls: string[]; // external image URLs
type: 'simple' | 'variable';
variations?: ExternalVariation[];
}
export interface ExternalVariation {
sku: string;
attributes: Record<string, string>; // e.g., { color: 'Red', size: 'L' }
price: number;
stockQuantity: number;
}
3. The Upsert Pattern (Check → Create or Update)
The core of any sync system is the upsert: if a product with the same SKU exists, update it; otherwise create it.
// src/upsert.ts
import { woo } from './client';
import type { ExternalProduct } from './types';
export async function findProductBySku(sku: string): Promise<number | null> {
try {
const { data } = await woo.get('products', { sku, per_page: 1 });
return data.length > 0 ? data[0].id : null;
} catch {
return null;
}
}
export async function upsertProduct(externalProduct: ExternalProduct): Promise<number> {
const existingId = await findProductBySku(externalProduct.sku);
const payload = buildProductPayload(externalProduct);
if (existingId) {
const { data } = await woo.put(`products/${existingId}`, payload);
console.log(`✓ Updated product ${externalProduct.sku} (ID: ${data.id})`);
return data.id;
} else {
const { data } = await woo.post('products', payload);
console.log(`✓ Created product ${externalProduct.sku} (ID: ${data.id})`);
return data.id;
}
}
4. Building the WooCommerce Payload
// src/payload.ts
import type { ExternalProduct } from './types';
export function buildProductPayload(product: ExternalProduct) {
return {
name: product.name,
type: product.type,
sku: product.sku,
description: product.description,
short_description: product.shortDescription,
regular_price: product.price.toFixed(2),
sale_price: product.salePrice ? product.salePrice.toFixed(2) : '',
manage_stock: true,
stock_quantity: product.stockQuantity,
status: 'publish',
images: product.imageUrls.map((src) => ({ src })),
categories: product.categories.map((name) => ({ name })),
};
}
Note: WooCommerce creates categories automatically by name if they don't exist. For better control, look up category IDs first and pass
{ id: X }instead.
5. Handling Variable Products and Variations
Variable products require two steps: create the parent, then create/update each variation.
// src/variations.ts
import { woo } from './client';
import type { ExternalVariation } from './types';
async function findVariationBySku(
productId: number,
sku: string
): Promise<number | null> {
const { data } = await woo.get(`products/${productId}/variations`, {
sku,
per_page: 1,
});
return data.length > 0 ? data[0].id : null;
}
export async function syncVariations(
productId: number,
variations: ExternalVariation[]
) {
for (const variation of variations) {
const existingId = await findVariationBySku(productId, variation.sku);
const payload = {
sku: variation.sku,
regular_price: variation.price.toFixed(2),
manage_stock: true,
stock_quantity: variation.stockQuantity,
attributes: Object.entries(variation.attributes).map(([name, option]) => ({
name,
option,
})),
};
if (existingId) {
await woo.put(`products/${productId}/variations/${existingId}`, payload);
console.log(` ↳ Updated variation ${variation.sku}`);
} else {
await woo.post(`products/${productId}/variations`, payload);
console.log(` ↳ Created variation ${variation.sku}`);
}
}
}
6. Batch Updates for Efficiency
The WooCommerce batch endpoint allows up to 100 creates/updates/deletes in a single request — far more efficient than individual calls:
// src/batch.ts
import { woo } from './client';
import { buildProductPayload } from './payload';
import type { ExternalProduct } from './types';
export async function batchUpdateProducts(products: ExternalProduct[]) {
const chunks = chunkArray(products, 50); // WooCommerce recommends max 50 per batch
for (const chunk of chunks) {
// Separate into creates and updates
const updates: Array<{ id: number } & ReturnType<typeof buildProductPayload>> = [];
const creates: Array<ReturnType<typeof buildProductPayload>> = [];
for (const product of chunk) {
const { data } = await woo.get('products', { sku: product.sku, per_page: 1 });
const payload = buildProductPayload(product);
if (data.length > 0) {
updates.push({ id: data[0].id, ...payload });
} else {
creates.push(payload);
}
}
await woo.post('products/batch', { create: creates, update: updates });
console.log(`Batch: ${creates.length} created, ${updates.length} updated`);
}
}
function chunkArray<T>(array: T[], size: number): T[][] {
const chunks: T[][] = [];
for (let i = 0; i < array.length; i += size) {
chunks.push(array.slice(i, i + size));
}
return chunks;
}
7. The Main Sync Runner
// src/sync.ts
import { upsertProduct } from './upsert';
import { syncVariations } from './variations';
import type { ExternalProduct } from './types';
// Simulate fetching products from your external system
async function fetchExternalProducts(): Promise<ExternalProduct[]> {
// Replace with your actual API call, database query, or CSV parse
return [
{
sku: 'TSHIRT-001',
name: 'Premium Cotton T-Shirt',
description: '<p>High-quality 100% cotton t-shirt.</p>',
shortDescription: 'Comfortable and stylish.',
price: 29.99,
stockQuantity: 0,
categories: ['Clothing', 'T-Shirts'],
imageUrls: ['https://example.com/tshirt.jpg'],
type: 'variable',
variations: [
{ sku: 'TSHIRT-001-S-RED', attributes: { Size: 'S', Color: 'Red' }, price: 29.99, stockQuantity: 15 },
{ sku: 'TSHIRT-001-M-RED', attributes: { Size: 'M', Color: 'Red' }, price: 29.99, stockQuantity: 22 },
{ sku: 'TSHIRT-001-L-BLU', attributes: { Size: 'L', Color: 'Blue' }, price: 31.99, stockQuantity: 8 },
],
},
];
}
async function runSync() {
console.log('Starting WooCommerce product sync...');
const products = await fetchExternalProducts();
let success = 0;
let failed = 0;
for (const product of products) {
try {
const productId = await upsertProduct(product);
if (product.type === 'variable' && product.variations) {
await syncVariations(productId, product.variations);
}
success++;
} catch (error) {
console.error(`✗ Failed to sync ${product.sku}:`, error);
failed++;
}
}
console.log(`\nSync complete: ${success} succeeded, ${failed} failed`);
}
runSync();
Run with:
npx tsx src/sync.ts
8. Scheduled Sync
For automatic syncing, use Node.js cron or a system scheduler:
npm install node-cron
// src/scheduler.ts
import cron from 'node-cron';
import { runSync } from './sync';
// Run every hour
cron.schedule('0 * * * *', async () => {
console.log(`[${new Date().toISOString()}] Running scheduled sync`);
await runSync();
});
console.log('Scheduler started — sync runs every hour');
Or use a Netlify/Vercel Scheduled Function if you're deploying to a serverless platform.
9. Error Handling and Logging
In production, log to a file or monitoring service:
// src/logger.ts
import fs from 'fs';
export function logError(sku: string, error: unknown) {
const entry = {
timestamp: new Date().toISOString(),
sku,
error: error instanceof Error ? error.message : String(error),
};
fs.appendFileSync('sync-errors.log', JSON.stringify(entry) + '\n');
console.error(`[ERROR] ${entry.timestamp} SKU ${sku}: ${entry.error}`);
}
Also implement retry logic for transient failures:
async function withRetry<T>(fn: () => Promise<T>, retries = 3): Promise<T> {
for (let attempt = 1; attempt <= retries; attempt++) {
try {
return await fn();
} catch (error) {
if (attempt === retries) throw error;
const delay = attempt * 1000;
console.log(`Attempt ${attempt} failed. Retrying in ${delay}ms...`);
await new Promise(res => setTimeout(res, delay));
}
}
throw new Error('Unreachable');
}
Conclusion
A robust WooCommerce product sync system built on the REST API gives you:
- Single source of truth — your external system or ERP owns the data
- Automation — no manual CSV imports
- Scalability — batch API handles hundreds of products efficiently
- Reliability — upsert pattern prevents duplicates
The pattern scales from small catalogues (10s of products) to large ones (thousands) when combined with proper batching, rate limiting, and scheduled execution.
Next steps: add a webhook from your ERP that triggers the sync immediately when a product changes — instead of waiting for the scheduled run.
Written by Dev Pattern LabsCore Engineering
Dev Pattern Labs is an engineering lab and digital consultancy specializing in custom Next.js web applications, WooCommerce REST API integrations, and workflow automation for growing businesses.
Recommended Companion Articles

WooCommerce Abandoned Cart Recovery via REST API and Webhooks
Recover lost revenue with automated WooCommerce cart recovery. Capture draft checkouts via webhooks, generate restore tokens, and send dynamic emails.

Building High-Performance Custom Endpoints in WooCommerce REST API
Create lightweight WP_REST_Controller endpoints in WooCommerce. Bypass heavy core payloads, reduce database queries, and return JSON responses under 50ms.

Building Headless WooCommerce Cart and Checkout in Next.js 15
Architect a high-converting headless WooCommerce cart and checkout flow with Next.js 15 App Router, CoCart REST endpoints, and Stripe payment elements.
