commerce-bridge
v1.0.1
Published
Unified marketplace ecommerce integrations library
Maintainers
Readme
CommerceBridge SDK

CommerceBridge SDK is a production-grade, open-source Node.js/TypeScript library that provides a unified API to interface with multiple e-commerce marketplaces and direct-to-consumer (D2C) channels.
Integrate once and manage listings, inventory, prices, orders, and shipments across multiple platforms seamlessly.
🚀 Supported Marketplaces & Channels
CommerceBridge currently supports 8 major e-commerce platforms out of the box. Below is the configuration credentials guide:
| Channel | Identifier | Credentials Object Schema | Auth Mechanism | Sandbox? |
| :--- | :--- | :--- | :--- | :---: |
| Amazon SP-API | 'amazon' | { sellerId, clientId, clientSecret, refreshToken } | LWA OAuth 2.0 | Yes |
| Flipkart | 'flipkart' | { appId, appSecret } | OAuth 2.0 Client Credentials | Yes |
| Snapdeal | 'snapdeal' | { clientId, apiKey, sellerToken } | Header Token Signatures | No |
| Meesho | 'meesho' | API Mode: { merchantId, apiKey }CSV Mode: { csvDirectory }Automation: { supplierUsername, supplierPassword } | API / CSV / Browser Automation | No |
| Shopify | 'shopify' | { shopName, adminAccessToken } | Admin Token Header | Yes |
| WooCommerce | 'woocommerce' | { storeUrl, consumerKey, consumerSecret } | Basic Auth over HTTPS | Yes |
| eBay | 'ebay' | { clientId, clientSecret, userToken } | OAuth 2.0 User Access Token | Yes |
| Walmart US | 'walmart' | { clientId, clientSecret } | Client Credentials Token | Yes |
✨ Key Features
- Unified Interface: Consistent methods (
getOrders,updateInventory,addProduct,createShipment) across all platforms. - Parallel Multi-Channel Broadcasting: Broadcast absolute inventory levels, relative stock changes (
modifyStock), and price shifts to all connected channels simultaneously in one asynchronous call. - Token-Bucket Rate Limiter: Configurable requests-per-second and burst ceilings. Intelligently pauses and refills request queues to avoid hitting marketplace rate limits.
- Exponential Backoff Retries: Automatic retries with randomized jitter on connection errors. Non-transient errors (like validation or auth failures) immediately bypass retries to avoid wasting API quotas.
- Automatic Log Sanitization: Integrated recursive credential masking guarantees that sensitive properties (like client secrets, tokens, and passwords) never leak into console outputs or logs.
- Event-Driven Telemetry: Subscribe to SDK-wide events (e.g., connection status, inventory updates, shipment creations) via a central event emitter.
📦 Installation
npm install commerce-bridge🔒 Security & Server-Side Execution
[!CAUTION] CommerceBridge must ONLY be executed in server-side/backend environments (Node.js, Deno, Bun, serverless functions, or backend APIs).
Do not bundle or run this library directly in client-side browser applications (such as React, Vue, Angular, or Svelte frontends). Doing so exposes your highly sensitive marketplace credential secrets, client keys, and OAuth secrets in the browser bundle, putting your seller accounts at risk.
💻 Quick Start
1. Initialize Connectors & Connections
import { ConnectorFactory } from 'commerce-bridge';
// Initialize Amazon SP-API Connector
const amazon = ConnectorFactory.create('amazon', {
marketplace: 'amazon',
credentials: {
sellerId: 'AMZN-SELLER-101',
clientId: 'lwa-client-id',
clientSecret: 'lwa-client-secret',
refreshToken: 'lwa-refresh-token'
}
});
// Initialize WooCommerce Store (Requires secure HTTPS)
const woocommerce = ConnectorFactory.create('woocommerce', {
marketplace: 'woocommerce',
credentials: {
storeUrl: 'https://my-store.com',
consumerKey: 'ck_xxx',
consumerSecret: 'cs_xxx'
}
});
// Establish authentication links
await amazon.connect();
await woocommerce.connect();2. Fetch and Normalize Orders
All connectors return normalized data structures, isolating your business logic from raw third-party payloads.
const orders = await amazon.getOrders();
console.log(orders[0]);
// Output:
// {
// id: '902-3112345-1234567',
// marketplace: 'amazon',
// status: 'READY_TO_SHIP',
// customer: { name: 'John Doe', email: '[email protected]' },
// shippingAddress: { addressLine1: '123 Pine St', city: 'Seattle', ... },
// items: [{ sku: 'PRODUCT-A', quantity: 1, price: 120.50 }],
// totalAmount: 120.50,
// currency: 'USD',
// createdAt: 2026-07-04T12:00:00.000Z
// }3. Multi-Channel Stock Broadcast
Use the MultiChannelManager to sync stock counts across multiple channels simultaneously in parallel.
import { multiChannelManager } from 'commerce-bridge';
// Register active channels
multiChannelManager.register('us-amazon', amazon);
multiChannelManager.register('store-woocommerce', woocommerce);
// Broadcast absolute inventory levels
await multiChannelManager.broadcastInventory([
{ sku: 'GLOBAL-TEE-M', quantity: 150 }
]);
// Or broadcast relative stock adjustments (+10 units to all channels)
await multiChannelManager.broadcastModifyStock('GLOBAL-TEE-M', 10);📡 Event Telemetry
CommerceBridge includes a central eventManager implementing the Node.js EventEmitter to listen for telemetry changes across channels.
import { eventManager } from 'commerce-bridge';
// Listen to connector changes
eventManager.on('connector.connected', (data) => {
console.log(`Connector registered: ${data.marketplace.toUpperCase()}`);
});
// Listen to inventory modifications
eventManager.on('inventory.updated', (data) => {
console.log(`Channel ${data.marketplace} updated SKU:`, data.items);
});🛠️ Custom Error Handling
CommerceBridge uses structured error classes to simplify diagnostics. Transient errors are automatically retried by the SDK.
import { AuthError, RateLimitError, ValidationError, MarketplaceError } from 'commerce-bridge';
try {
await amazon.getOrders();
} catch (error) {
if (error instanceof RateLimitError) {
console.error(`Rate limited! Try again after: ${error.retryAfterMs} ms`);
} else if (error instanceof AuthError) {
console.error(`Authentication credentials invalid: ${error.message}`);
} else if (error instanceof ValidationError) {
console.error(`Local model validation failed: ${error.message}`);
} else if (error instanceof MarketplaceError) {
console.error(`Marketplace server error [HTTP: ${error.statusCode}]: ${error.message}`);
}
}⚙️ Configuration Options
The connector configuration (MarketplaceConfig) supports fine-grained tuning for rate limiters, retry logic, and custom logging:
interface MarketplaceConfig {
marketplace: string;
credentials: Record<string, any>;
sandbox?: boolean; // Enable sandbox/testing endpoints
logger?: CommerceBridgeLogger; // Pluggable Logger (Winston, Console, etc.)
rateLimit?: {
requestsPerSecond: number;
burst?: number;
};
retry?: {
maxRetries: number;
initialDelayMs: number;
maxDelayMs?: number;
factor?: number; // Exponential scale multiplier
};
}📖 API Reference
Core Exports
| Export | Type | Description |
| :--- | :--- | :--- |
| ConnectorFactory | Class | Factory registry to register and instantiate marketplace connectors. |
| multiChannelManager | Instance | Global manager coordinating parallel stock, pricing, and update broadcasts across registered channels. |
| eventManager | Instance | Central event broker dispatching telemetry and connection events. |
| BaseConnector | Class | Base connector class providing rate limit, retry, log sanitization, and lifecycle wrappers. |
| CommerceBridgeLogger | Interface | Pluggable logger interface (supports custom loggers like Winston/Pino). |
Marketplace Connector Interface
Every connector registered in CommerceBridge implements the standard MarketplaceConnector interface:
| Method | Return Type | Description |
| :--- | :---: | :--- |
| connect() | Promise<void> | Prepares authentication, requests tokens, and sets up HTTP clients. |
| getOrders(filters?) | Promise<Order[]> | Fetches and returns normalized orders. |
| updateInventory(items) | Promise<void> | Standardizes bulk absolute stock updates. |
| updatePrice(items) | Promise<void> | Standardizes bulk price updates. |
| modifyStock(sku, quantity) | Promise<void> | Modifies stock levels relatively (handles relative additions/subtractions). |
| createShipment(data) | Promise<Shipment> | Books shipping orders or initiates marketplace manifests (Easy Ship, etc.). |
🔌 Extensibility: Adding a New Marketplace
CommerceBridge is designed to scale. Adding a new channel does not require changing core code:
- Subclass
BaseConnectorand implement the methods:import { BaseConnector, Order, Product } from 'commerce-bridge'; export class CustomConnector extends BaseConnector { async connect(): Promise<void> { // Authenticate with custom marketplace } async getOrders(): Promise<Order[]> { // Fetch and map to normalized Order[] } // Implement inventory, shipments, cancellation, etc... } - Register the class in the factory registry:
import { ConnectorFactory } from 'commerce-bridge'; import { CustomConnector } from './connectors/CustomConnector'; ConnectorFactory.register('custom', CustomConnector); - Instantiate normally:
const custom = ConnectorFactory.create('custom', config);
🤝 Contributing
Contributions are welcome! Please read our Contributor Guidelines to get started. To run tests locally:
npm run test📄 License
This project is licensed under the MIT License - see the LICENSE file for details. Use it freely in commercial, open-source, or private projects. Attribution is highly appreciated!
