Shopify
Link products and collections from a Shopify store with @cms/shopify, and keep the CMS and the store in step from one admin page.
@cms/shopify is a plugin for sites whose products live in Shopify and whose
pages live here. One instance is one store. It adds:
- fields made from the instance,
shop.product(),shop.products()andshop.collection(), with a search picker that goes through the plugin’s routes, so no Admin API credential reaches the browser - a Shopify admin page: every product and collection next to its CMS page, Create page (one or many), Link to existing page, Where is this used?, a Launch checklist per collection, and a Health tab that finds pages linking deleted or archived items, two pages for one item, pages and products whose publishing disagrees, and stored copies that drifted
- a banner at the top of an editor whose document links a deleted or archived item
hydrate()from@cms/shopify/client, which swaps stored snapshots for live storefront data on the website, and an opt-in write-back of each page’s URL into a Shopify metafieldshop.assertUnique, the hook behindunique: true, andshop.listColumn()/shop.summaryMedia()for the list and summary thumbnails every project otherwise writes by hand
pnpm add @cms/shopify
// cms.config.tsx
import { config, entity, text } from "@cms/config";
import { path } from "@cms/paths";
import { shopify } from "@cms/shopify";
export const shop = shopify({
store: "acme", // acme.myshopify.com
admin: {
clientId: process.env.SHOPIFY_ADMIN_CLIENT_ID,
clientSecret: process.env.SHOPIFY_ADMIN_CLIENT_SECRET,
},
});
const productPage = entity("product_page", {
versions: true,
fields: [
shop.product("product", { required: true, unique: true, fillTitle: true }),
text("title", { required: true }),
path("path", { source: (doc) => `/products/${doc.product?.handle ?? ""}` }),
],
hooks: { beforeDraftSave: shop.assertUnique, beforePublish: shop.assertUnique },
admin: {
summary: { fields: ["title", "product"], title: ({ data }) => data.title, media: shop.summaryMedia("product") },
list: { fields: ["title", "product"], columns: [shop.listColumn("product"), { label: "Title", render: ({ data }) => data.title }, "updatedAt"] },
},
});
export default config({
entities: [productPage],
plugins: [shop],
// ...
});
The plugin adds no entities, so there is no migration to run. The fields are plain
object and array fields and
migrate like any other.
Options
| Option | Type | Description |
|---|---|---|
store |
string |
The store’s myshopify handle (acme for acme.myshopify.com). A missing one warns at boot, and the pickers and the Shopify page answer 502 SHOPIFY_ERROR until it is set. |
admin |
{ clientId, clientSecret } or { accessToken } |
Admin API credentials of a custom app with read_products: a Dev Dashboard app’s client id and secret (exchanged for a token at request time), or a legacy app’s access token. Read them from env; missing ones warn at boot, and the pickers and the Shopify page answer 502 SHOPIFY_ERROR until they are set. |
apiVersion |
string |
The Admin API version. Default: "2026-07". |
roles |
string[] |
Roles, beyond admins, that may use the pickers and open the Shopify page. Default: []. |
pages |
Record<entity, { template?, prefill? }> |
What Create page fills in beyond the reference and the title; see Create page. |
channel |
string |
The sales channel the website sells through, by its name in Shopify: "Online Store", or a headless storefront’s channel. The launch checklist, Health and the catalog’s channel filter check products against it. Needs read_publications. Default: "Online Store". |
redirects |
the @cms/redirects instance |
Pass the project’s redirects instance and Health offers Add a redirect when a page follows its item’s new handle; see Handle drift. |
writeBack |
{ url, namespace?, key? } |
Writes each published page’s URL into a metafield of the item it links; see URL write-back. Off by default. |
name |
string |
The instance name. Default: "shopify". Give each store its own. |
Only the store handle reaches the admin bundle; admin is read on the server. A missing option
fails cms dev and cms start with the list of what’s missing, and no other command.
Fields
Every field stores a snapshot of the item, so pages render and build paths without a request. Shopify stays the source of truth: the plugin only reads from it, and the Health tab finds snapshots that went stale.
| Field | Stores | Admin input |
|---|---|---|
shop.product(name, opts) |
{ id, handle, title, image, status } |
A search dialog with product cards. The chip shows the item’s state (archived, draft in Shopify, not in Shopify any more, renamed) and links to the Shopify admin, the Shopify page and Where is this used? |
shop.products(name, opts) |
an ordered list of product snapshots | The same dialog with multi-select, plus Add all from collection…, which fills the list from a collection to trim and reorder afterwards. Chips reorder by drag. Takes min and max like any array field. |
shop.collection(name, opts) |
{ id, handle, title, image } |
The same, for collections |
id is Shopify’s global id (gid://shopify/Product/123), image the featured image’s CDN URL,
and status the product’s status in Shopify (active, draft or archived, stored as text).
Chips and picker cards also show what Shopify sells the product at now: the price range, the
variant count, Sold out (with read_inventory, for a product that tracks inventory and has no
variant for sale, counting variants that keep selling at zero) and
Not on the sales channel (with read_publications). These are read live and never stored.
Options beyond title, description, required and shared:
unique: true(single fields): no two published documents of the entity may link the same item. Translations of one document may. Enforced byshop.assertUnique, below.fillTitle: true(single fields): picking an item also fills the document’stitlewhen it’s empty. Only for a page’s own field: inside a block the document isn’t about the item.
A field made from an instance needs that instance in plugins; config() throws otherwise. The
fields work anywhere a field does: at the top of an entity or global, and inside objects, arrays,
unions and rich-text blocks. Only an entity’s top-level single field makes a document the page
of an item, which is what the Shopify page’s coverage and Create page are about.
One page per product
Plugins can’t add before-hooks, so unique: true is enforced by a hook the entity registers:
hooks: { beforeDraftSave: shop.assertUnique, beforePublish: shop.assertUnique },
It refuses the save with an error on the field when another published document, outside the writer’s translation group, links the same item. It runs on draft save too, so the editor hears about it before publishing, and it composes with the entity’s other hooks:
beforePublish: async (data, existing, ctx) => checkStock(await shop.assertUnique(data, existing, ctx)),
Two stores
A second store is a second instance, and both can sit on one entity:
const shopCh = shopify({ name: "shopify-ch", store: "acme-ch", admin: { /* … */ } });
const shopEu = shopify({ name: "shopify-eu", store: "acme-eu", admin: { /* … */ } });
entity("product_page", {
fields: [shopCh.product("product_ch", { unique: true }), shopEu.product("product_eu", { unique: true })],
hooks: {
beforeDraftSave: async (data, existing, ctx) =>
shopEu.assertUnique(await shopCh.assertUnique(data, existing, ctx), existing, ctx),
// beforePublish: the same
},
});
Each instance’s page, routes and checks read and write only that instance’s fields. The plugin has no notion of the same product in two stores: to pair them, create the page from one store’s Shopify page, then Link to existing page from the other’s.
The Shopify page
At /admin/plugins/<name>/store, a sidebar item of its own under Plugins in the default sidebar. A custom
sidebar places it where the products live, page("store", { plugin: "shopify", label: "Shopify" })
next to the product pages, or with plugin("shopify"). Admins always see it; other roles when
listed in roles.
| Tab | What it shows | Actions |
|---|---|---|
| Overview | How many products and collections have a page (a translated page counts once) and a published one, the open problems, and the entities whose fields link this store | Check again |
| Products | The store’s products, searchable and filtered by their CMS side (without a page, with a page, draft page only, published page), by their status in Shopify, and by product type, vendor, tag, collection and sales channel, in numbered pages with the admin’s rows-per-page choice, each next to its CMS pages (one row per page, its translations as locale badges). Selecting a whole page offers to select every matching item without a page, across pages. A CMS-side filter checks at most the first 5,000 items of the search, and says so when it stops there | Create page (one, or every selected item), Link to existing page…, Where is this used?, Open in Shopify admin |
| Collections | The same, for collections (searched by title). A row expands to the collection’s products, in its order, each with its pages | The same |
| Launch | The launch checklist of a collection | Open page, Create page, Open in Shopify |
| Health | Problems, grouped: an item deleted in Shopify, an item archived, a published page whose product the sales channel doesn’t sell (or that is a draft in Shopify), two pages linking one item from the same field, a product on the sales channel whose page is a draft in every language, or links it only in a pending draft (these two checks read what the website shows, not the draft), an item changed in Shopify since it was linked (a new title or image is cosmetic until refreshed; a new handle moves the page, see Handle drift). Each lists every document and the place in it, down to the block (blocks[2].product_rail.source.products.items[0]), drafts included |
Refresh snapshots (one document, or every stale one), Move to new path, Unlink / Remove from here, Check again |
Where is this used? lists every document and place that references an item: pages, rails, nav menus, synced blocks, in published content and pending drafts. Run it before archiving something in Shopify. A reference inside a synced block is reported once, on the synced block, not on every page that includes it.
Create page
Create page creates a draft (or a published document on an entity without drafts) in the
default locale, as the signed-in editor, with the reference and, when the entity has a title
field, the item’s title. Items that already have a page are skipped. pages.<entity> adds to that:
shopify({
// ...
pages: {
product_page: {
template: () => ({ blocks: [{ _type: "product_hero" }] }),
prefill: ({ product }) => ({
metadata: { title: product?.seo.title ?? product?.title, description: product?.seo.description },
}),
},
},
});
prefill gets { product } or { collection }: the snapshot plus description (plain text),
seo, and for products productType, vendor and tags. What template and prefill return
must pass the entity’s validation, as a save would.
Refresh and unlink
Refresh snapshots rewrites every snapshot in a document from Shopify, keeping anything the project stores next to it. Unlink clears a top-level reference or removes an item from its list. Both write the way the document is kept: a published document without a pending draft is published again; an unpublished document, or one with a pending draft, gets a draft save, and the toast says so. Neither is run on a document the editor can’t update.
Handle drift
When a product’s handle changes, a page path built from it (a path() from @cms/paths, or any
slug field holding /…) still holds the old handle. Health lists each such page with the path the
new handle gives: /products/brie → /products/brie-de-meaux, the segment equal to the old handle
replaced. Move to new path writes the new path and refreshes the page’s snapshots in one write,
kept the way the document is kept (as above).
With @cms/redirects installed, pass its instance and the move can also
leave a 301 from the old path, so links to it keep working:
const redirectsPlugin = redirects();
const shop = shopify({ /* … */, redirects: redirectsPlugin });
export default config({ plugins: [redirectsPlugin, shop] /* … */ });
The redirect is created as the signed-in editor, so their role needs to create redirects.
Launch checklist
Pick a collection (a drop, a seasonal selection) and the Launch tab checks each of its products:
| Check | Passes when |
|---|---|
| Has a page | a page entity’s top-level field links it |
| Page published | one of its pages is published, in any language |
| Active in Shopify | its status is active |
| On the sales channel | it is published on channel; unknown (not a blocker) without read_publications |
| Has an image | it has a featured image |
A product passing all of them is Ready; the others list their blockers, with a link to the page, to Create page, or to the product in the Shopify admin.
In the editor
A document that links a deleted or archived item gets a banner above its fields, naming the items
and linking to Health. It shows to admins and to the roles of the instance. The plugin adds
nothing to the dashboard: pages missing and open problems live on its own page, under Overview and
Health.
Open in CMS from Shopify
The Shopify page opens an item’s page from its id: /admin/plugins/<name>/store?id=<id> goes to
the item’s page (in the default locale when it is translated), or offers Create page when it
has none. The id is the numeric one or a gid; add &type=collection for a collection.
To add Open in CMS to the product screen of the Shopify admin, give the custom app an
admin link extension. A link opens a path
of the app’s application_url, so set that to the CMS’s address, and Shopify appends the item’s
id to it:
# shopify.app.toml
application_url = "https://cms.example.com"
embedded = false
# extensions/open-in-cms/shopify.extension.toml
[[extensions]]
name = "Open in CMS"
handle = "open-in-cms"
type = "admin_link"
[[extensions.targeting]]
target = "admin.product.action.link"
url = "/admin/plugins/shopify/store?type=product"
Deploy it with shopify app deploy. The editor needs to be signed in to the CMS first; the admin
opens its dashboard after a sign-in, not the link.
On the website: hydrate()
Snapshots are what the page was saved with. hydrate() swaps every product and collection
snapshot in a query result, however deep (a page’s product, a rail’s products in a block), for
what the storefront says now: title, handle, image, price and availability. It sends one
Storefront API nodes request per 250 items, with the public Storefront token only:
import { hydrate } from "@cms/shopify/client";
const { data } = await cms.get("home");
const home = await hydrate(data, {
storefront: { store: "acme", token: env.PUBLIC_STOREFRONT_TOKEN, country: "CH", language: "FR" },
});
home.blocks[0].products.map((product) => (product.missing ? null : product.price));
Each snapshot gets price ({ min, max, currency }, products only), availableForSale and
missing. An item the storefront doesn’t have (deleted, archived, or not on its channel) stays in
the result, marked missing: true with its stored title and image, so the website decides
whether to hide it. country and language set the storefront’s @inContext.
URL write-back
With writeBack, publishing a page writes its URL into a metafield of the item its top-level
field links, so Shopify themes, feeds and sitemaps can link to it; unpublishing removes it. On an
entity with versions: false, where every save is live, each create and update writes it.
shopify({
// ...
writeBack: {
namespace: "cms", // default
key: "url", // default
url: ({ document }) => `https://www.example.com${document.path}`,
},
});
url gets the published document and returns the address, or null to clear the metafield. An
item has one metafield, so a translated page writes its default-locale URL only. It runs after the
publish: a Shopify failure is reported (to Sentry, with @cms/sentry) and never fails the publish.
Without writeBack, the plugin makes no write to Shopify.
Access scopes
| Scope | Needed for |
|---|---|
read_products |
everything |
read_publications |
the sales channel: the launch checklist, Health’s publishing checks, the channel filter and badge |
read_inventory |
Sold out on chips and picker cards |
write_products |
writeBack only |
The plugin reads the app’s scopes and works without the optional ones: what they’d show stays unknown rather than failing.
Calling the routes
Everything the page does is a plugin route under
/api/plugins/<name>/, typed for a project’s client: info, search, nodes,
collection-products, collection-members, catalog, catalog-ids, facets, launch,
pages, health, usage, and POST create-pages, link, refresh, unlink, move-path. A Shopify failure answers 502 SHOPIFY_ERROR with Shopify’s message.
const { data } = await cms.route("/plugins/shopify/health");
data.problems.filter((problem) => problem.kind === "missing");
Moving a hand-written picker onto the package
Projects that built their own picker store { id, handle, title, featured_image } in an object
field. The package’s snapshot is { id, handle, title, image, status }, so the move is:
- Replace the
object("product", { fields: [...], admin: { components: { input } } })withshop.product("product", { ... }), keeping the field name. cms migration generate: the JSONB shape diff asks whetherfeatured_imagebecameimage. Answer yes, so the stored images are kept; it also addsstatus, empty for now. Review the migration, thencms migration apply.- Replace the uniqueness hook (raw SQL) with
shop.assertUnique, and the hand-written list column and summary media withshop.listColumn()andshop.summaryMedia(). - Open the Shopify page’s Health tab: every document shows as stale (its
statusis empty). Refresh them once and the snapshots are complete.
Code that reads the field keeps working, except for the featured_image key.
Previous
Redirects
Next
Synced blocks