npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@chazify/smartcart-hydrogen

v1.3.7

Published

Smart Cart for Hydrogen - Upsells, Cross-sells, BOGO & Recommendations

Downloads

404

Readme

@chazify/smartcart-hydrogen

Smart Cart for Shopify Hydrogen - Upsells, Cross-sells, BOGO & Product Recommendations

npm version License: MIT

Installation

npm install @chazify/smartcart-hydrogen

Setup

1. Get Your Public Key

  1. Login to your Chazify SmartCart admin at smartcart.chazify.com
  2. Click on "Settings" in the bottom left corner of the dashboard
  3. In the "API Security Token" section, click "Generate API Token" if you haven't already
  4. 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:

  1. In the Settings page (bottom left corner), scroll to the "Allowed Domains" section
  2. Add your storefront domain(s), for example:
    • mystore.myshopify.com (production)
    • staging.myshopify.com (staging)
  3. 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:...), add localhost to 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_here

Security 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 onCartUpdated to trigger useRevalidator().revalidate() to update cart state
  • Custom Event: A chazify:cart-updated event 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 sendBeacon for 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:

  1. JWT Authentication: Token is cryptographically signed and can't be forged
  2. Shop Validation: Token is tied to your specific store
  3. 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 localhost for 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 localhost to 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 .env file
  • Restart your development server after changing .env

See SECURITY.md for detailed security documentation.

Support

License

MIT