@chazify/smartcart-hydrogen
v1.3.7
Published
Smart Cart for Hydrogen - Upsells, Cross-sells, BOGO & Recommendations
Downloads
404
Maintainers
Readme
@chazify/smartcart-hydrogen
Smart Cart for Shopify Hydrogen - Upsells, Cross-sells, BOGO & Product Recommendations
Installation
npm install @chazify/smartcart-hydrogenSetup
1. Get Your Public Key
- Login to your Chazify SmartCart admin at smartcart.chazify.com
- Click on "Settings" in the bottom left corner of the dashboard
- In the "API Security Token" section, click "Generate API Token" if you haven't already
- Click "Show" to reveal the key, then click "Copy" to copy it to your clipboard
2. Configure Allowed Domains
⚠️ REQUIRED: You must whitelist the domains that can use your public key:
- In the Settings page (bottom left corner), scroll to the "Allowed Domains" section
- Add your storefront domain(s), for example:
mystore.myshopify.com(production)staging.myshopify.com(staging)
- Click "Add Domain" for each domain
Important Security Notes:
- Production domains MUST be added or the API will reject requests with 403 Forbidden
- API requests from unauthorized domains are always blocked
🛠️ Local Development: To test your Hydrogen storefront locally (
http://localhost:...), addlocalhostto your allowed domains in the Smart Cart settings. This enables HTTP requests from localhost even though the production API enforces HTTPS for all other domains.
3. Add Key to Environment Variables
In your Hydrogen storefront, add to .env:
CHAZIFY_SMARTCART_PUBLIC_KEY=your_public_key_hereSecurity Note: The public key:
- Is safe to expose in browser requests
- Only works from domains in your whitelist
- Can be regenerated anytime in the admin dashboard
4. Pass Key to Provider
In your app/root.jsx:
import {SmartCartProvider, SmartCart} from '@chazify/smartcart-hydrogen';
import {useLoaderData} from 'react-router';
import '@chazify/smartcart-hydrogen/index.css';
// In your loader
export async function loader({context}) {
const {cart} = context;
const smartcartPublicKey = context.env.CHAZIFY_SMARTCART_PUBLIC_KEY;
return {cart, smartcartPublicKey};
}
export default function App() {
const {cart, smartcartPublicKey} = useLoaderData();
return (
<SmartCartProvider
shop="your-store.myshopify.com"
cart={cart}
smartcartPublicKey={smartcartPublicKey}
countryCode="US"
>
<PageLayout>{children}</PageLayout>
<SmartCart />
</SmartCartProvider>
);
}Usage
Trigger cart drawer from anywhere
import {useSmartCart} from '@chazify/smartcart-hydrogen';
function ProductCard() {
const {toggleDrawer} = useSmartCart();
return <button onClick={toggleDrawer}>Add to Cart</button>;
}Show product recommendations
import {ProductRecommendations} from '@chazify/smartcart-hydrogen';
export default function CartPage() {
return (
<div>
<Cart />
<ProductRecommendations />
</div>
);
}ProductRecommendations on a Page (with cart drawer)
When using ProductRecommendations on a page (outside the cart drawer), you'll want the cart to open after adding products and trigger a revalidation:
import {ProductRecommendations, SmartCartProvider, SmartCart} from '@chazify/smartcart-hydrogen';
import {useLoaderData, useRevalidator} from 'react-router';
import '@chazify/smartcart-hydrogen/index.css';
export async function loader({context}) {
const {cart, storefront, env} = context;
return {
cart: await cart.get(),
smartcartPublicKey: env.PUBLIC_CHAZIFY_SMARTCART_API_KEY,
countryCode: storefront.i18n.country || 'US',
};
}
export default function RecommendationsPage() {
const {cart, smartcartPublicKey, countryCode} = useLoaderData();
const revalidator = useRevalidator();
// Revalidate cart after adding from recommendations
const handleCartUpdated = () => {
revalidator.revalidate();
};
return (
<SmartCartProvider
shop="your-store.myshopify.com"
cart={cart}
smartcartPublicKey={smartcartPublicKey}
countryCode={countryCode}
>
<div style={{padding: '2rem'}}>
<h1>You May Also Like</h1>
<ProductRecommendations onCartUpdated={handleCartUpdated} />
</div>
<SmartCart />
</SmartCartProvider>
);
}ProductRecommendations Props
| Prop | Type | Required | Default | Description |
| ------------------ | ---------- | -------- | -------- | -------------------------------------------------------------------------- |
| onAddToCart | function | ❌ | - | Custom add-to-cart handler (variantId, quantity, productData) => Promise |
| cart | object | ❌ | - | Hydrogen cart object (uses context cart if not provided) |
| showRuleProducts | array | ❌ | [] | Additional products from show rules to merge into recommendations |
| openCartOnAdd | boolean | ❌ | true* | Whether to open cart drawer after adding (* false when inside drawer) |
| isInsideDrawer | boolean | ❌ | false | Set to true when rendered inside SmartCartDrawer to prevent re-opening |
| onCartUpdated | function | ❌ | - | Callback when cart is updated (use for revalidation) |
Behavior Notes:
- On a page: Cart drawer opens automatically after adding a product (unless
openCartOnAdd={false}) - Inside drawer: Cart drawer does NOT re-open (already open)
- Revalidation: Use
onCartUpdatedto triggeruseRevalidator().revalidate()to update cart state - Custom Event: A
chazify:cart-updatedevent is dispatched on window after successful add
Configuration
The Smart Cart automatically fetches configuration from your Chazify SmartCart API using the provided token. You can also provide initial config:
<SmartCartProvider
shop="your-store.myshopify.com"
cart={cart}
smartcartPublicKey={smartcartPublicKey}
countryCode="US"
initialConfig={{
cartTitle: 'Your Cart',
recommendationMode: 'collections',
collectionRecommendations: [{collectionId: 123456789, collectionHandle: 'trending'}],
}}
>
{children}
</SmartCartProvider>API
SmartCartProvider Props
| Prop | Type | Required | Default | Description |
| -------------------- | ----------------- | -------- | ------------------------------- | ------------------------------------------------------------ |
| shop | string | ✅ | - | Your Shopify store domain (e.g., your-store.myshopify.com) |
| cart | object | ✅ | - | Hydrogen cart object from loader |
| smartcartPublicKey | string | ✅ | - | Your Chazify SmartCart public key |
| countryCode | string | ❌ | US | ISO 3166-1 alpha-2 country code for multi-currency support |
| apiUrl | string | ❌ | https://smartcart.chazify.com | API URL |
| initialConfig | SmartCartConfig | ❌ | - | Pre-loaded configuration |
| enableAnalytics | boolean | ❌ | false | Enable session/analytics tracking (see below) |
Analytics & Session Tracking
By default, analytics is disabled for optimal performance. When enabled:
- Creates a session when cart drawer opens (once per session)
- Tracks recommendation clicks and add-to-cart events
- Uses
sendBeaconfor non-blocking, fire-and-forget tracking
// Enable analytics for conversion tracking
<SmartCartProvider
shop="your-store.myshopify.com"
cart={cart}
smartcartPublicKey={smartcartPublicKey}
enableAnalytics={true} // Opt-in for analytics
>useSmartCart Hook
const {
config, // Smart Cart configuration
isLoading, // Loading state
isDrawerOpen, // Drawer open state
openDrawer, // Open cart drawer
closeDrawer, // Close cart drawer
toggleDrawer, // Toggle cart drawer
cart, // Hydrogen cart object
recommendations, // Product recommendations
enableAnalytics, // Whether analytics tracking is enabled
} = useSmartCart();Multi-Currency Support
The Smart Cart supports multi-currency pricing through Shopify Markets. Pass the customer's country code to get localized prices:
// Example: Get country from Hydrogen context
export async function loader({context}) {
const {cart} = context;
const {storefront, env} = context;
const countryCode = storefront.i18n.country || 'US';
const smartcartPublicKey = context.env.PUBLIC_CHAZIFY_SMARTCART_API_KEY;
return {
cart: await cart.get(),
smartcartPublicKey,
countryCode,
};
}
export default function App() {
const {cart, smartcartPublicKey, countryCode} = useLoaderData();
return (
<SmartCartProvider
shop="your-store.myshopify.com"
cart={cart}
smartcartPublicKey={smartcartPublicKey}
countryCode={countryCode}
>
<PageLayout>{children}</PageLayout>
<SmartCart />
</SmartCartProvider>
);
}Supported Country Codes: Any ISO 3166-1 alpha-2 country code (e.g., US, GB, CA, AU, DE, FR, JP, etc.)
How It Works:
- Product recommendations automatically fetch prices in the specified currency
- Prices are converted using Shopify's Admin API
contextualPricing - Currency symbols and amounts are displayed correctly for each market
- Falls back to USD if no country code is provided
Requirements:
- Your Shopify store must have Shopify Markets configured
- Products must have prices set for the target markets
See CURRENCY_SUPPORT.md for detailed documentation.
Features
- ✅ Smart cart drawer with real-time updates
- ✅ Product recommendations (manual & collection-based)
- ✅ Multi-currency support via Shopify Markets
- ✅ BOGO promotions (Buy One Get One)
- ✅ Auto-add upsells with discounts
- ✅ Show recommendations popup/on-cart
- ✅ Secure public key authentication
- ✅ Customizable styling
- ✅ TypeScript support
- ✅ SSR-safe (works with Hydrogen's streaming SSR)
- ✅ Works with Hydrogen's cart API
- ✅ Performance optimized (optional analytics with sendBeacon)
Admin Configuration
Configure your cart settings at smartcart.chazify.com/cart:
- Cart UI: Customize colors, text, buttons
- Product Recommendations: Manual selection or collection-based
- Rules: Create BOGO, auto-add, and show recommendation rules
- Trigger Products: Set specific products that trigger upsells
- Public Key: Generate and manage your secure public keys
Security
Your API token uses a three-layer security model:
- JWT Authentication: Token is cryptographically signed and can't be forged
- Shop Validation: Token is tied to your specific store
- Domain Whitelisting: Token only works from authorized domains
Best Practices
- ✅ Store token in environment variables (
.env) - ✅ Add all your domains to the whitelist in admin dashboard
- ✅ Use
localhostfor local development - ✅ Never commit tokens to version control
- ✅ Pass via server-side loader when possible
- ✅ Regenerate token if compromised
- ❌ Don't use
*(all domains) in production
Common Issues
403 Forbidden - "Domain not authorized"
- Add your domain to the "Allowed Domains" whitelist in SmartCart admin
- Make sure you added the full domain (e.g.,
mystore.myshopify.com) - For local development, add
localhostto the whitelist
401 Unauthorized - "Invalid token"
- Check that you copied the complete token from the dashboard
- If you regenerated the token, update it in your
.envfile - Restart your development server after changing
.env
See SECURITY.md for detailed security documentation.
Support
- Dashboard: smartcart.chazify.com
- Issues: GitHub Issues
- Email: [email protected]
License
MIT
