JAMstack commerce platform SDK for Cloudflare infrastructure
npm install @cartflare/button-sdkA modern, TypeScript-first e-commerce SDK for building customizable buy buttons and shopping cart experiences. Optimized for Cloudflare infrastructure and JAMstack architectures.
``bashUsing Bun (recommended)
bun install cartflare-button-sdk
$3
`html
`Quick Start
$3
`typescript
import { createCartFlare } from 'cartflare-button-sdk';// Initialize CartFlare
const cartflare = createCartFlare({
merchantId: 'your-merchant-id',
apiUrl: 'https://api.cartflare.com', // Optional
storefrontToken: 'your-storefront-token' // Optional
});
// Initialize the SDK
await cartflare.init();
// Add a product to cart
await cartflare.addToCart('variant-id', 1);
// Proceed to checkout
await cartflare.checkout();
`$3
`tsx
import { CartFlareProvider, useCartFlare } from 'cartflare-button-sdk/react';function App() {
return (
merchantId: 'your-merchant-id',
ui: {
components: {
product: {
layout: 'vertical',
buttonDestination: 'cart'
}
}
}
}}>
);
}
function ProductComponent() {
const { addToCart, cart } = useCartFlare();
const handleAddToCart = async () => {
await addToCart('variant-id', 1);
};
return (
);
}
`Configuration
$3
`typescript
interface CartFlareConfig {
// Required
merchantId: string;
// Optional API settings
apiUrl?: string;
storefrontToken?: string;
// Cart behavior
cart?: {
startOpen?: boolean;
popup?: boolean;
sticky?: boolean;
contents?: {
note?: boolean;
noteDescription?: string;
};
templates?: {
footer?: string;
};
};
// UI customization
ui?: {
components?: {
product?: ProductComponentConfig;
cart?: CartComponentConfig;
};
styles?: StyleConfig;
};
// Event handlers
events?: {
afterInit?: (component: unknown) => void;
afterRender?: (component: unknown) => void;
beforeDestroy?: (component: unknown) => void;
};
}
`$3
`typescript
interface ProductComponentConfig {
layout?: 'vertical' | 'horizontal';
buttonDestination?: 'cart' | 'checkout' | 'modal';
contents?: {
img?: boolean;
imgWithCarousel?: boolean;
title?: boolean;
description?: boolean;
price?: boolean;
button?: boolean;
buttonWithQuantity?: boolean;
quantity?: boolean;
};
text?: {
button?: string;
outOfStock?: string;
unavailable?: string;
};
order?: string[];
DOMEvents?: {
[key: string]: (event: Event, target: HTMLElement) => void;
};
}
`$3
`typescript
interface CartComponentConfig {
contents?: {
title?: boolean;
note?: boolean;
discountForm?: boolean;
};
text?: {
title?: string;
total?: string;
button?: string;
empty?: string;
noteDescription?: string;
notice?: string;
};
popup?: boolean;
startOpen?: boolean;
sticky?: boolean;
}
`Implementation Guide
$3
1. Install the SDK
`bash
bun install cartflare-button-sdk
`2. Create a CartFlare instance
`typescript
import { createCartFlare } from 'cartflare-button-sdk';
const cartflare = createCartFlare({
merchantId: 'your-merchant-id'
});
`3. Initialize the SDK
`typescript
await cartflare.init();
`$3
#### Vanilla JavaScript
`html
`#### React Integration
`tsx
import { ProductComponent } from 'cartflare-button-sdk/react';function MyProduct() {
return (
productId="product-id"
config={{
layout: 'vertical',
contents: {
img: true,
title: true,
price: true,
button: true
}
}}
/>
);
}
`$3
#### Programmatic Cart Operations
`typescript
// Add to cart
await cartflare.addToCart('variant-id', 2, {
customField: 'custom-value'
});// Update line item
await cartflare.updateLineItem('line-item-id', 3);
// Remove line item
await cartflare.removeLineItem('line-item-id');
// Clear entire cart
await cartflare.clearCart();
// Get current cart state
const currentCart = cartflare.cart;
// Subscribe to cart changes
const unsubscribe = cartflare.subscribeToCart((cart) => {
console.log('Cart updated:', cart);
});
// Cleanup subscription
unsubscribe();
`#### React Hooks
`tsx
import { useCartFlare } from 'cartflare-button-sdk/react';function CartManager() {
const { cart, addToCart, updateLineItem, removeLineItem, clearCart, checkout } = useCartFlare();
return (
Shopping Cart ({cart?.lineItems.length || 0} items)
{cart?.lineItems.map((item) => (
{item.title}
${item.price}
type="number"
value={item.quantity}
onChange={(e) => updateLineItem(item.id, parseInt(e.target.value))}
/>
))}
);
}
`$3
#### CSS Variables
`css
:root {
--cartflare-product-max-width: 500px;
--cartflare-product-title-color: #333;
--cartflare-product-price-color: #666;
--cartflare-button-background: #007bff;
--cartflare-button-color: white;
}
`#### Configuration-based Styling
`typescript
const cartflare = createCartFlare({
merchantId: 'your-merchant-id',
ui: {
styles: {
product: {
'@media (min-width: 601px)': {
'max-width': '400px'
},
title: {
'font-size': '18px',
'font-weight': '600',
'color': '#333'
},
price: {
'font-size': '16px',
'color': '#007bff'
},
button: {
'background-color': '#007bff',
'color': '#ffffff',
'padding': '12px 24px',
':hover': {
'background-color': '#0056b3'
}
}
}
}
}
});
`$3
#### Global Events
`typescript
// Listen to cart events
document.addEventListener('cartflare:item:added', (event) => {
console.log('Item added:', event.detail);
});document.addEventListener('cartflare:item:removed', (event) => {
console.log('Item removed:', event.detail);
});
document.addEventListener('cartflare:checkout:initiated', (event) => {
console.log('Checkout started:', event.detail);
});
`#### Component Events
`typescript
const cartflare = createCartFlare({
merchantId: 'your-merchant-id',
events: {
afterInit: (component) => {
console.log('CartFlare initialized');
},
afterRender: (component) => {
console.log('Component rendered');
},
beforeDestroy: (component) => {
console.log('Component about to be destroyed');
}
}
});
`#### Custom DOM Events
`typescript
const productComponent = cartflare.createComponent('product', {
productId: 'product-id'
});// Add custom DOM event handlers
productComponent.config.ui.components.product.DOMEvents = {
click: (event, target) => {
console.log('Product clicked:', target);
},
mouseover: (event, target) => {
console.log('Product hovered:', target);
}
};
`Advanced Usage
$3
`typescript
// Display multiple products
const productIds = ['product-1', 'product-2', 'product-3'];productIds.forEach((productId, index) => {
const container = document.getElementById(
product-${index});
const component = cartflare.createComponent('product', { productId });
component.render(container);
});
`$3
`typescript
const cartflare = createCartFlare({
merchantId: 'your-merchant-id',
ui: {
components: {
product: {
order: ['img', 'title', 'description', 'price', 'quantity', 'button'],
contents: {
imgWithCarousel: true,
description: true,
buttonWithQuantity: true
}
}
}
}
});
`$3
`typescript
const cartflare = createCartFlare({
merchantId: 'your-merchant-id',
cart: {
startOpen: false,
popup: true,
sticky: true
},
ui: {
components: {
cart: {
popup: true,
startOpen: false,
sticky: true,
contents: {
title: true,
note: true,
discountForm: true
}
}
}
}
});
`API Reference
$3
#### Methods
-
init(): Promise - Initialize the SDK
- addToCart(variantId: string, quantity?: number, properties?: Record - Add item to cart
- updateLineItem(lineItemId: string, quantity: number): Promise - Update item quantity
- removeLineItem(lineItemId: string): Promise - Remove item from cart
- clearCart(): Promise - Clear entire cart
- checkout(): Promise - Initiate checkout
- subscribeToCart(callback: (cart: Cart | null) => void): () => void - Subscribe to cart changes
- createComponent(type: 'product' | 'cart', options?: any): Component - Create UI component
- destroyComponent(component: Component): void - Destroy UI component#### Properties
-
cart: Cart | null - Current cart state (readonly)$3
#### Cart
`typescript
interface Cart {
id: string;
lineItems: LineItem[];
subtotal: number;
total: number;
discount: number;
note?: string;
createdAt: string;
updatedAt: string;
}
`#### LineItem
`typescript
interface LineItem {
id: string;
variantId: string;
title: string;
price: number;
quantity: number;
properties?: Record;
}
`#### Product
`typescript
interface Product {
id: string;
title: string;
description?: string;
price: number;
compareAtPrice?: number;
currency?: string;
images: ProductImage[];
variants: ProductVariant[];
}
`Development
$3
`bash
Clone the repository
git clone https://github.com/cartflare/cartflare-button-sdk.git
cd cartflare-button-sdkInstall dependencies
bun installDevelopment mode
bun run devBuild for production
bun run buildRun tests
bun run testType checking
bun run typecheckLinting
bun run lint
`$3
`
src/
├── core/ # Core SDK implementation
│ └── cartflare.ts
├── components/ # UI components
│ ├── cartflare.ts # Vanilla JS components
│ └── react/ # React components
│ └── cartflare.tsx
├── types/ # TypeScript definitions
│ └── cart-types.ts
├── styles/ # Default CSS styles
│ └── cartflare.css
└── index.ts # Main entry point
`$3
-
dist/index.esm.js - ES Module build
- dist/index.js - CommonJS build
- dist/cartflare.js - UMD build
- dist/cartflare.min.js - Minified UMD build
- dist/index.d.ts` - TypeScript declarations- Chrome 60+
- Firefox 60+
- Safari 12+
- Edge 79+
MIT License - see LICENSE file for details.
1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests for new functionality
5. Submit a pull request
- Documentation: https://docs.cartflare.com
- Issues: GitHub Issues
- Community: Discord Server