Updated

How to Add an AI Chatbot to a Headless Shopify Store: a Complete Guide

Rui JiangRui Jiang - Feb 10, 2026
Add AI Chatbot to Headless Shopify Store

Running a headless Shopify store means you’ve decoupled your storefront from Shopify’s built-in theme system. You might be using Hydrogen, Next.js, Gatsby, a custom React app, or any other frontend framework—while Shopify handles your products, orders, and payments behind the scenes via the Storefront API.

The good news: adding Shoply AI chatbot to a headless store is simple. You don’t need the Shopify theme editor or any Shopify app embed blocks. Just a few lines of HTML and JavaScript.


How It Works

Shoply AI’s chatbot loads as a lightweight script that runs independently of Shopify’s theme system. All you need is:

  1. Install Shoply AI on your Shopify store
  2. A small configuration object with your store key
  3. The Shoply AI script loaded from our CDN

That’s it - no npm packages to install, no build steps, and no framework-specific wrappers needed. The script creates its own container on the page, so you don’t need to add one.


Step 1: Install Shoply AI

New to Shoply AI? Install the app  on your Shopify store to get started. Once installed, you can use the headless integration below to add the chatbot to your custom storefront.

Moving an Existing Store to Headless or Hydrogen?

Keep Shoply AI installed. You don’t need to reinstall it, and you won’t lose your settings. A Hydrogen or other headless storefront still runs on the same Shopify store. Your Shoply installation, plan, product index, and every setting in the Shoply admin belong to that store, not to your theme.

The only change is how the chat loads. A theme store loads Shoply through the app embed in the theme editor. A headless storefront doesn’t use the theme, so add the script below to your frontend code instead.


Step 2: Add the Script

Add a single script tag to your HTML. Replace your-store.myshopify.com with your actual Shopify store domain (the .myshopify.com one, not your custom domain):

html
<script src="https://assets.shoplyai.ai/shoplyjs/shoply_chat_core.js" shoply-site-key="your-store.myshopify.com" defer="defer"></script>

This script handles everything: rendering the chat widget, connecting to the AI, displaying product recommendations, and more.

For the best experience — including multi-currency, localized UI, and product-page context — set window.shoply_data before the script loads:

html
<script type="text/javascript"> window.shoply_data = { store_key: "your-store.myshopify.com", language_code: "en", country_code: "US", cart: { "currency": "USD" }, } </script> <script src="https://assets.shoplyai.ai/shoplyjs/shoply_chat_core.js" defer="defer"></script>
FieldDescriptionExample
store_keyRequired. Your Shopify store’s permanent .myshopify.com domain"your-store.myshopify.com"
language_codeLanguage for the chatbot UI and answers"en", "fr", "es"
country_codeCustomer’s country, used for market-specific answers"US", "CA", "GB"
cartCart info including currency. Used to determine which currency to display for products{ "currency": "USD" }
product_idOptional. The current product’s numeric Shopify ID (see Product Pages)"8012345678"
product_title, product_description, product_imagesOptional. The current product’s name, description, and image URLs. Used by the “Question About This Product?” button (see Product Pages)"Rain Jacket", "<p>Waterproof shell</p>", ["https://cdn.shopify.com/..."]
customer_idOptional. The logged-in customer’s numeric Shopify customer ID"9903183265907"
customer_first_name, customer_last_nameOptional. The logged-in customer’s name, shown on their chat messages"Ana", "Lopez"

Use your storefront’s current locale for language_code, country_code, and the cart currency. In Hydrogen, these come from context.storefront.i18n and the cart.


Product Pages

Shoply answers product-specific questions (“Is this waterproof?”) when it knows which product the shopper is viewing. It finds the product in one of two ways:

  1. From the page URL (automatic). When a shopper asks a question, the chat sends the current page URL. If the URL contains /products/<handle>, as Hydrogen’s default product route does, Shoply looks up that product by its handle. No extra code is needed.
  2. From product_id (optional). If your product URLs don’t contain /products/<handle>, set product_id to the product’s numeric ID.

The URL is enough for ordinary questions. The “Question About This Product?” button needs more: it opens the chat with the product’s name, a product highlight, and suggested questions. The chat switches to this product view only when product_images holds at least one URL; it uses product_title for the name and product_id and product_description to write the highlight and questions, so set all four. On a theme store, Shopify’s app embed fills these in. On a headless store, set them yourself on product pages.

Use the number only. The Storefront API and Hydrogen return IDs like gid://shopify/Product/8012345678. Send "8012345678". A full gid:// value prevents Shoply from finding the product.

On Hydrogen? You can usually skip the product-page code. With automatic Hydrogen integration, Shoply fills in these product fields from your Hydrogen page data and keeps them current as shoppers move between pages.

Single-Page Apps (Hydrogen, Next.js, React)

Headless storefronts change pages without reloading, so the script loads once. The chat reads window.shoply_data again for every question, so update the existing object when the shopper changes pages. Don’t replace it with a new object, because the chat keeps the object it started with.

javascript
// When a product page opens Object.assign(window.shoply_data, { product_id: "8012345678", // numeric ID only product_title: "Rain Jacket", product_description: "<p>Waterproof shell with taped seams.</p>", product_images: ["https://cdn.shopify.com/s/files/.../rain-jacket.jpg"], }) // When the shopper leaves the product page for (const key of ["product_id", "product_title", "product_description", "product_images"]) { delete window.shoply_data[key] }

Once the product fields are set, open chat from product-page links to give shoppers a direct way to ask about the item.


Complete Example

Here’s a complete working example. You can also find this file hosted at shoplyai.ai/headless.html :

html
<html> <head> <meta charset="utf-8"> </head> <body> <div> Hello World! </div> <script src="https://assets.shoplyai.ai/shoplyjs/shoply_chat_core.js" shoply-site-key="shoplyaics.myshopify.com" defer="defer"></script> </body> </html>

Open this page in a browser and you’ll see the Shoply AI chatbot floating widget appear in the corner, ready to help your customers.


Hydrogen Example

In a Hydrogen project, add both scripts to the root layout in app/root.tsx so they load once for every page. Hydrogen’s Content Security Policy only runs scripts that carry its nonce, so pass the nonce to both tags:

tsx
// app/root.tsx import {useNonce} from '@shopify/hydrogen'; export function Layout({children}: {children?: React.ReactNode}) { const nonce = useNonce(); return ( <html lang="en"> <head>{/* ...your existing head tags... */}</head> <body> {children} <script nonce={nonce} suppressHydrationWarning dangerouslySetInnerHTML={{ __html: `window.shoply_data = window.shoply_data || { store_key: "your-store.myshopify.com", language_code: "en", country_code: "US", cart: {currency: "USD"} };`, }} /> <script nonce={nonce} src="https://assets.shoplyai.ai/shoplyjs/shoply_chat_core.js" defer /> {/* ...your existing <ScrollRestoration /> and <Scripts nonce={nonce} /> ... */} </body> </html> ); }

With automatic Hydrogen integration, you’re usually done: skip the product-route code below. If your storefront doesn’t meet its requirements, on your product route (for example app/routes/products.$handle.tsx), set the product fields so the “Question About This Product?” button works, and so product questions work even if your URLs don’t contain /products/<handle>. Request images(first: 5) { nodes { url } } in the route’s product query:

tsx
useEffect(() => { const data = (window as Window & {shoply_data?: Record<string, unknown>}).shoply_data; if (!data) return; Object.assign(data, { product_id: product.id.split('/').pop(), // "gid://shopify/Product/123" -> "123" product_title: product.title, product_description: product.descriptionHtml, product_images: product.images.nodes.map((image) => image.url), }); return () => { for (const key of ['product_id', 'product_title', 'product_description', 'product_images']) { delete data[key]; } }; }, [product]);

If shoppers can sign in, you can also set customer_id, customer_first_name, and customer_last_name from Hydrogen’s Customer Account API. The chat then labels their messages with their name and links the conversation to their customer account. Chat works without these fields.


Allow Shoply in Your Content Security Policy

If your storefront sends a Content Security Policy (CSP), the browser blocks scripts and connections that the policy doesn’t list. Hydrogen storefronts usually have one. If the chat icon doesn’t appear, open the browser console. A “Refused to load” or “Refused to connect” error means the policy is blocking Shoply.

Add these sources to your policy:

DirectiveSourcesWhy
script-srchttps://assets.shoplyai.aiThe chat script, which loads a versioned copy of itself from the same host
connect-srchttps://api.shoplyai.ai, wss://api.shoplyai.aiChat answers, settings, and the live answer stream
connect-srchttps://d1xiepy4977gv7.cloudfront.netChat interface translations
connect-srchttps://n40zofyfcg.execute-api.us-west-1.amazonaws.comShopper events such as add to cart
connect-srchttps://api.ipify.org, https://api.radar.ioApproximate shopper location for region-specific answers
connect-srchttps://your-store.myshopify.comHydrogen only: links the shopper’s cart to the chat and lets the chat’s Add to Cart button add to your cart. Hydrogen’s createContentSecurityPolicy already allows this through shop.storeDomain
img-srchttps://cdn.shopify.com, https://d1xiepy4977gv7.cloudfront.net, https://cdn-js-scripts.s3.us-west-2.amazonaws.comProduct images, your chat icon and background, and the placeholder image
style-src'unsafe-inline'The chat widget adds its own styles at runtime

If your project uses Hydrogen’s createContentSecurityPolicy (Shopify’s starter template calls it in app/entry.server.tsx), add the sources there:

ts
const {nonce, header, NonceProvider} = createContentSecurityPolicy({ shop: { checkoutDomain: context.env.PUBLIC_CHECKOUT_DOMAIN, storeDomain: context.env.PUBLIC_STORE_DOMAIN, }, scriptSrc: ["'self'", 'https://cdn.shopify.com', 'https://assets.shoplyai.ai'], connectSrc: [ "'self'", 'https://api.shoplyai.ai', 'wss://api.shoplyai.ai', 'https://d1xiepy4977gv7.cloudfront.net', 'https://n40zofyfcg.execute-api.us-west-1.amazonaws.com', 'https://api.ipify.org', 'https://api.radar.io', ], imgSrc: [ "'self'", 'data:', 'https://cdn.shopify.com', 'https://d1xiepy4977gv7.cloudfront.net', 'https://cdn-js-scripts.s3.us-west-2.amazonaws.com', ], styleSrc: ["'self'", "'unsafe-inline'", 'https://cdn.shopify.com'], });

Keep any sources your storefront already lists. If the console still reports a blocked Shoply address after these changes, contact us  and we’ll help.


Automatic Hydrogen Integration

On a theme store, Shopify’s app embed and web pixel give Shoply the current product, add-to-cart events, and completed orders. A Hydrogen storefront has neither, so Shoply does that work from the chat script instead. You only add the script and allow Shoply in your Content Security Policy. Shoply then handles three things:

  1. Product pages. Shoply reads the product from your Hydrogen page data and fills in product_id, product_title, product_description, and product_images. You don’t need the product-page code.
  2. Shopper events. Shoply reports additions made through Hydrogen’s cart forms (CartForm with the LinesAdd action), and product pages opened from Shoply links, such as products recommended in chat. You don’t need to call window.shoplyLogEvent, unless some add-to-cart buttons don’t use CartForm (see below).
  3. Orders credited to Shoply. Shoply saves the chat session on the shopper’s cart as an attribute named _shoply_session_id, and checks it again after every cart change. Shoply’s checkout tracking reads it, so orders are credited to the chat even when checkout runs on your .myshopify.com domain. The attribute is stored with the order, so you’ll see it under the order’s additional details in your Shopify admin.

Turning It On

There’s nothing to turn on. Every day, and shortly after you install Shoply AI, Shoply checks your store’s sales channels in Shopify. When it finds Shopify’s Hydrogen sales channel, automatic Hydrogen integration starts on your storefront’s next page load. If you add the Hydrogen channel later, allow up to a day. It only runs on Hydrogen pages, so a theme storefront on the same store keeps working as before.

What Automatic Hydrogen Integration Needs

Your storefront needs to follow Shopify’s Hydrogen starter template in these ways:

  • The root route loads Hydrogen’s consent data, including the public storefrontAccessToken, at the top level of its data, as the starter template does for analytics. Data nested one level deeper (for example under data) isn’t found.
  • The cart uses Hydrogen’s default cart cookie, readable by page scripts, or the root route returns the cart as the starter template does.
  • Add-to-cart buttons use Hydrogen’s CartForm. Additions made with fetcher.submit() or a custom fetch call aren’t detected; send those yourself.
  • Product routes load the product into page data as product, and product URLs contain /products/<handle>.
  • The Shoply AI app stays installed, so its checkout tracking keeps running on Shopify’s checkout.

If your storefront already sends shopper events with window.shoplyLogEvent, add headless_auto_tracking: false to window.shoply_data so they aren’t counted twice. That setting turns off only the shopper events: product pages and order credit stay automatic.

Add-to-Cart Buttons That Don’t Use CartForm

Shoply only sees additions made through Hydrogen’s CartForm. If an add-to-cart button calls fetcher.submit(), your own API route, or the Storefront API directly, report the addition yourself once it succeeds. Shopify’s IDs from Hydrogen (gid://shopify/ProductVariant/… and gid://shopify/Product/…) can be sent as they are:

tsx
// After your add-to-cart call succeeds window.shoplyLogEvent?.('product_added_to_cart', { cartLine: { merchandise: { id: selectedVariant.id, // variant ID title: selectedVariant.title, price: { amount: selectedVariant.price.amount, currencyCode: selectedVariant.price.currencyCode, }, product: {id: product.id}, // product ID }, quantity, }, referrer: window.location.href, });

Send one event per added product, and only for buttons that don’t use CartForm: those are already reported. If you’d rather report every addition yourself, set headless_auto_tracking: false (see above) and call window.shoplyLogEvent for all of them. The shopper events guide lists the full event format.


What Works Differently on a Headless Store

Some Shoply features depend on Shopify’s theme. Here’s what changes on a headless storefront and what to do about it:

FeatureOn a headless storefrontWhat to do
AI chatWorks with the script aboveNothing beyond Step 2
Shoply admin settingsApply as usualNothing; settings are saved per store
Add to Cart button on products in chatHydrogen: adds to the shopper’s Hydrogen cart through the Storefront API and refreshes your cart count. It needs the same storefront setup as automatic Hydrogen integration. Other frameworks: works only if your storefront serves Shopify’s theme cart routes (/cart/add.js, /cart/update.js, /cart.js) and sets window.Shopify.routes.rootIf neither applies, in the Shoply admin, open Customize AI Search → AI Search: Product Results and set Action Button in Search Results to View Product or No Button. This setting also controls the button on products shown in chat
Product links in chatUse each product’s Online Store URL from Shopify, which can point at your .myshopify.com domain or an older theme domainHydrogen: product and collection links on those domains open on your Hydrogen site automatically, so keep /products/<handle> and /collections/<handle> routes. Other frameworks: keep products published to the Online Store sales channel and make sure your main Shopify domain points at your headless site. After launch, click a product in the chat and confirm it opens on your headless domain
AI Search replacing your search pageTheme onlyUse the AI Search API to power your own search page
Shopper events (add to cart, product views)Shopify’s web pixel doesn’t run on headless pagesHydrogen: nothing, with automatic Hydrogen integration, for add to cart through CartForm and product pages opened from Shoply links. Other frameworks: send them with window.shoplyLogEvent; see shopper events for headless stores
Orders credited to ShoplyTracked automatically on Shopify’s checkoutHydrogen: nothing, with automatic Hydrogen integration, wherever checkout runs. Other frameworks: keep checkout on a subdomain of your storefront’s domain (for example shop.example.com and checkout.example.com). Shoply links the order to the chat through a cookie set for that shared domain

Framework Integration Tips

Since the integration is a single script tag, it works with any framework:

  • Hydrogen: Add the scripts to app/root.tsx with the CSP nonce, as shown in the Hydrogen example
  • Next.js / React: Add the <script> tag in your layout component or use next/script
  • Gatsby: Add in gatsby-ssr.js or use the <Helmet> component
  • Vue / Nuxt: Add to your app template or use a plugin to inject the script
  • Static sites: Paste the snippet directly into your HTML

Get Started

Already using Shoply AI on your Shopify store and want to add it to your headless frontend? Just grab your store_key and follow the steps above—it takes less than a minute.

You can also add search through the AI Search API alongside the chat integration.

Need help? Book a meeting with us  and we’ll walk you through the setup.

Happy selling!

Continue reading