Shopify Hydrogen
Install
Nine steps in your Hydrogen app. Each one works on its own, so you can deploy them together or one at a time. This guide is for version 0.5 or later.
1. Add the package#
npm install @aiptimise/hydrogenIt is an ES module with TypeScript types. react and @shopify/hydrogen are peer dependencies: the module uses yours.
2. Set the environment variables#
In Shopify admin, Hydrogen → your storefront → Storefront settings → Environments and variables, add the two values Aiptimise gave you to each environment that should run Aiptimise (Production, and Preview while you test):
| Variable | Type | Value |
|---|---|---|
AIPTIMISE_SITE_ID | Plain | The site id (a UUID). |
AIPTIMISE_SITE_SECRET | Secret | The site secret. It is read on the server only and never reaches the browser. |
AIPTIMISE_PRODUCT_JSONLD | Plain, optional | off keeps your own Product JSON-LD whatever Aiptimise's setting says (step 6). Leave it unset otherwise. |
For local development, put both in your .env. Without them, every Aiptimise route answers 404 and the other helpers do nothing, so a branch without them still builds and runs.
Deploying with --env-file
shopify hydrogen deploy --env-file <file> replaces the environment's variables for that deployment instead of adding to them. If you deploy that way, the file must hold all of your storefront's variables as well as the two above, or the deployment runs without them.3. Add the proxy and llms.txt routes#
// app/routes/apps.aiptimise.$.tsx
export {aiptimiseProxyLoader as loader} from '@aiptimise/hydrogen';// app/routes/[llms.txt].tsx
export {aiptimiseLlmsTxtLoader as loader} from '@aiptimise/hydrogen';/apps/aiptimise/* is the path theme stores use, so links in your llms.txt and AI pages are the same on every Shopify storefront. It serves your store's llms.txt, the AI sitemap, an AI page per product and the IndexNow key file. AI crawlers that fetch it show up in your Aiptimise crawler analytics.
4. Add the AI crawler rules to robots.txt#
Keep your robots.txt route and pass its body through aiptimiseRobotsTxt:
// app/routes/[robots.txt].tsx
import {aiptimiseRobotsTxt} from '@aiptimise/hydrogen';
export async function loader({request, context}) {
// Your robots.txt body, built as it is today.
const body = await aiptimiseRobotsTxt({request, context}, yourRobotsTxt());
return new Response(body, {headers: {'Content-Type': 'text/plain'}});
}- It appends Aiptimise's groups for AI search and fetch crawlers and a
Sitemap:line for/apps/aiptimise/sitemap.xml. - Your rules win: a user-agent your robots.txt already names keeps your group, and Aiptimise's group for it is left out. To block a crawler, name it in your own rules.
- Nothing is appended until you have agreed to the robots.txt change with Aiptimise, the same consent theme stores give.
- The rules are cached for a day, so updates reach you without a deploy. If Aiptimise cannot be reached, your body is returned unchanged.
5. Add head links to the home and product pages#
<link rel="alternate"> tags that point crawlers to the store's llms.txt and each product's AI page. Load Aiptimise's settings next to your own data and wrap your meta export.// app/routes/products.$handle.tsx
import {aiptimiseMeta, loadAiptimise} from '@aiptimise/hydrogen';
export async function loader({request, context, params}) {
const [{product}, aiptimise] = await Promise.all([
context.storefront.query(PRODUCT_QUERY, {variables: {handle: params.handle}}),
loadAiptimise({request, context}),
]);
return {product, aiptimise};
}
export const meta = aiptimiseMeta(yourMeta, {page: 'product'});// app/routes/_index.tsx
import {aiptimiseMeta, loadAiptimise} from '@aiptimise/hydrogen';
export async function loader({request, context}) {
const [yourData, aiptimise] = await Promise.all([
loadYourHomeData(context),
loadAiptimise({request, context}),
]);
return {...yourData, aiptimise};
}
export const meta = aiptimiseMeta(yourMeta, {page: 'home'});aiptimiseMeta returns your tags first and unchanged, then adds the links: your llms.txt on the home page, the product's AI page on a product page. A link you already print is not added twice. It reads the product id from your loader's product.id; if your loader names it differently, say where it is:
export const meta = aiptimiseMeta(yourMeta, {
page: 'product',
productId: ({data}) => data.item.id,
});loadAiptimise makes one request to Aiptimise per storefront host every five minutes, in the background (context.waitUntil) while the last answer is used. A page never waits for it: until the first answer arrives (a new deployment, an empty cache), the page renders without the links and with the product block off. If Aiptimise cannot be reached, the last answer stays in use; if it refuses (an unknown site, a host not listed for your site), nothing of Aiptimise's is added. It never throws. Errors in your own meta function still throw as before.
6. Add the product block field#
Aiptimise publishes each product's Product JSON-LD to a storefront-readable product metafield, aiptimise.product_jsonld. Add one field to the product selection of your product query:
// app/routes/products.$handle.tsx: your product query
const PRODUCT_QUERY = `#graphql
query Product($handle: String!) {
product(handle: $handle) {
id
title
# … your fields …
aiptimiseJsonLd: metafield(namespace: "aiptimise", key: "product_jsonld") {
value
}
}
}
`;Write the field out
The module also exports it asAIPTIMISE_PRODUCT_FRAGMENT, but Hydrogen's GraphQL codegen can't follow an imported string, so interpolating it would cost the query its generated types. Copy the field as above.The data comes with your product, cached like the rest of the query: nothing calls Aiptimise while a product page renders. Until the block is switched on, or while the metafield is empty, nothing changes. Once Aiptimise switches it on for your site (only with your agreement), aiptimiseMeta replaces your Product node with Aiptimise's when all of this holds:
- your product route prints exactly one Product node in a
script:ld+jsondescriptor (at the top level or in@graph), withoffers; - the product's metafield holds a Product with the same
@idas yours.
Aiptimise's document carries no price data: no offers, price, currency, sale price or availability. Your node's offers are copied into it unchanged, so price and stock always come from your page, as your Merchant Center feed expects. In any other case your descriptors come back exactly as your meta returned them, and your BreadcrumbList, Organization and other tags are never touched. If your loader doesn't return the product as product, say where the field is:
export const meta = aiptimiseMeta(yourMeta, {
page: 'product',
aiptimiseJsonLd: ({data}) => data.item.aiptimiseJsonLd,
});To turn the block off yourself at any time, set AIPTIMISE_PRODUCT_JSONLD=off in your Oxygen environment and redeploy: your own block comes back on every page. The decision is made in your loader, so it holds on client-side navigations too.
7. Add visit analytics#
Put <AiptimiseAnalytics> inside your <Analytics.Provider>, with your store's permanent myshopify.com domain:
// app/root.tsx
import {AiptimiseAnalytics} from '@aiptimise/hydrogen';
<Analytics.Provider cart={data.cart} shop={data.shop} consent={data.consent}>
<AiptimiseAnalytics shop="your-store.myshopify.com" />
<PageLayout {...data}>
<Outlet />
</PageLayout>
</Analytics.Provider>Then allow Aiptimise in connect-src:
// app/entry.server.tsx
const {nonce, header, NonceProvider} = createContentSecurityPolicy({
shop: {checkoutDomain: …, storeDomain: …},
connectSrc: ['https://app.aiptimise.com'],
});The component renders nothing and ships in your bundle, so script-src needs no change. It registers with the provider as Aiptimise and is ready at once, so it never holds back your other analytics. It acts only for shoppers who arrive from an AI assistant, and stores nothing in the browser without analytics consent: see What is sent.
8. Carry the AI visit to the order#
Checkout runs on Shopify's checkout domain, which cannot read your storefront's cookies, so the AI visit travels on the cart: Shopify copies cart attributes onto the order, where Aiptimise reads them. In your cart route's action, after the cart mutation:
// app/routes/cart.tsx
import {updateAiptimiseCartAttributes} from '@aiptimise/hydrogen';
export async function action({request, context}) {
const {cart} = context;
// … your switch over CartForm actions sets `result` …
const cartId = result?.cart?.id;
const headers = cartId ? cart.setCartId(result.cart.id) : new Headers();
await updateAiptimiseCartAttributes(request, cart, {cartId});
// … return as before …
}It acts only when <AiptimiseAnalytics> has stored an AI visit (its cookies, set only with consent); for every other shopper it makes no request. For an AI visitor it reads the cart's attributes once and writes _aiptimise_ref, _aiptimise_visit and _aiptimise_engine only when they are missing or changed, keeping your own attributes. Your cart query fragment must select attributes { key value }, as Hydrogen's default does. It never throws. Requires version 0.4 or later.
9. Deploy to a preview, then production#
Aiptimise answers only for the hostnames listed for your site. Each Oxygen preview deployment gets its own hostname, so send us the preview URL and wait for our go-ahead before you test (it takes effect within a minute of us adding it). Your production domain is listed when we set up your site.
Deploy the preview, run the checks in Verify and troubleshoot, then deploy to production.