# Build my own streaming store on Crystallize, like Screen Universe

I want a storefront for my business that works like **Screen Universe** (https://screen-universe.superfast.shop), a demo store built on Crystallize: A streaming service for film history on Crystallize subscriptions: plans with a free trial, pause, upgrade and metered downloads, films to rent or buy one-off, and a home that reorders for each profile in the household.

The content model and the wiring below are proven in that store: keep them for the features I want, and rename things to fit my trade. If a feature doesn't fit my business, leave its parts out rather than forcing it. Everything I see is mine to decide: brand, colours, typography, layout, copy and pages. Don't copy the demo's look; build my brand.

What the demo does: subscriptions, free trials, metered usage, digital goods, vector personalisation, explainable ranking, video, multiple markets, multi-currency. It is B2C, in English, Norwegian, Swedish, Dutch; my markets and languages may differ.

## How to work with me

- You need to run commands, edit files and use MCP tools. If you can't (for example in a plain chat), tell me, and suggest I paste this prompt into Claude Code, Cursor or another coding agent instead.
- Ask your questions a few at a time (three to five), in the order of the steps below, and suggest a sensible default for each so I can just say yes. Ask each thing once, even where two lists overlap, and ask the ones that change the build first. Don't start a step before the one before it is done.
- The technical detail below is for you. Talk to me in plain words, and explain a choice only when I need to make it.
- Keep the folder empty until step 5, apart from `.env.local`.
- Never ask me to paste an access token secret into the chat, and tell me not to paste a filled-in command or its output either. Tell me which command to run or which file to put it in, and I'll do it.
- Before you create or change anything in Crystallize, show me the plan (shapes, pieces, topics, price variants, markets) and wait for my yes. Before an import, show me a sample of five items.
- Use the Crystallize skills (the `skills` MCP tool, or the use-crystallize plugin) for how-to: `content-model`, `information-architecture`, `taxonomy`, `data-creation`, `mass-operations`, `pricing`, `query`, `mutation`, `js-api-client`, `responsive-images`, `payments`, and when this store needs them `subscriptions`, `bookable-resources`, `vector-ranking` and `permissions`. Where this prompt and a skill disagree, the skill wins. Check the live schemas with the MCP instead of guessing field names.
- When something I asked for isn't possible in Crystallize the way I pictured it, say so and offer the closest thing that is.
- **The storefront never reads from the Core API on customer-facing pages.** Products, public prices, stock and content come from the Discovery API and the Catalogue API; confidential prices (negotiated B2B price lists) from the Catalogue API on the server.
- **Use the Shop API for everything about customers:** carts, checkout, customers, orders (including orders created directly, such as renewals), order meta, pipeline stages, payments and subscription contracts. Take the customer identifier from the server session, never from the browser. The Core API is for setup scripts, back-office tools, scheduled jobs and what the Shop API can't do, always on the server and never once per page view.

## Step 1: Crystallize tenant, tokens and MCP

Ask me:
1. Do I have a Crystallize account and a tenant for this store? If not, I sign up for free at https://app.crystallize.com/signup and create an empty tenant. Ask for its **tenant identifier**.
2. Do I have access tokens? If not, tell me: in the Crystallize App, go to **Settings → Access Tokens → Generate a new token**, name it, and keep the ID and the secret (the secret is shown once). A token acts with its user's role, so while we build, that user needs to be Tenant Admin (or have a role that can write shapes, pieces, topics, items and prices and run mass operations). Once the store is built, switch the MCP to a token from a read-only user.
3. Is the Crystallize MCP connected, with write access? Check that you have its write tools (`run-mass-operation`, `mutate-core`), not only the read tools (`tenant-overview`, `fetch-content-model`): with only the read tools, it was added without `?exposeWrite=true`. If it's missing, have me run this in my terminal with my own token, then restart you:
   ```bash
   npx add-mcp "https://mcp.crystallize.com/mcp?exposeWrite=true" \
     --header "X-Crystallize-Access-Token-Id: <token id>" \
     --header "X-Crystallize-Access-Token-Secret: <token secret>"
   ```
   If the MCP can't be connected in my tool, say so and fall back to scripts that call the Crystallize APIs with the tokens from `.env.local`.
   In Claude Code, also suggest the Crystallize skills: `/plugin marketplace add crystallizeapi/ai`, then `/plugin install use-crystallize@crystallize-ai`. The plugin brings its own read-only Crystallize MCP entry with placeholder credentials: keep using the one added above (and add `&exposeSkills=false` to its URL once the plugin's skills are installed).
4. Confirm the connection with `tenant-overview`, and tell me what's already in the tenant. If it isn't empty, ask whether to build next to what's there or in a fresh tenant.

The storefront needs the tenant identifier and its own credentials: an access token pair for the Shop API (server only), and a static auth token if Discovery and the Catalogue API are secured. Don't reuse the admin build token in production. Put them in `.env.local` (have me fill in the secrets) and make sure `.env*` is in `.gitignore`.

## Step 2: my business and my brand

Ask me:
- What I sell, who buys it, and what makes us different. My brand name and a one-line pitch.
- My markets, currencies and languages, and my VAT/tax setup.
- Where my product data lives today: a spreadsheet or CSV, an export from Shopify, WooCommerce or another platform, a PIM or ERP, my current website, or nothing yet. Where my product images are.
- My brand: logo (SVG if I have it), colours, typefaces, tone of voice, and two or three sites whose look I like. If I have no brand guide, propose a direction from my answers and show it before building pages.
- Where it should run: my own domain, and hosting (suggest Vercel for Next.js).

Then ask what is particular to this kind of store:

- What do I stream or sell: films, courses, music, software? Which titles are included in a membership, and which are rent or buy only?
- My tiers: names, what each includes (streams, quality, downloads), monthly and yearly prices per market, and the length of the free trial.
- Any metered usage (downloads, seats, credits): how much is included, and the price above that?
- Add-ons sold as separate subscriptions (channels, packs)?
- My markets, currencies, VAT rate and languages.
- Do I hold the rights and the files for every video? Full titles or clips? Do I need DRM? Crystallize's playlists are public URLs, so paid full titles need a DRM-protected video host.
- Which dimensions describe taste in my catalogue (genre, mood, era…)? Per-profile or per-household recommendations?
- My payment provider for recurring billing: Crystallize keeps the contracts and the usage, but charges nothing itself.

## Step 3: the content model

Create this in my tenant with the MCP, renamed to fit my trade, after I have approved the plan. Keep the structure: it is what the storefront's features depend on.

Build in dependency order, since mass operations run in sequence with no rollback: pieces and shapes (empty first, then their components), topic maps (at most 30 topics per `topic/create`), price variants, markets and VAT types, the folder tree (two to four levels, five to twelve per level), and only then items. Use lowercase-hyphen identifiers. Decide now which fields are translated and which are discoverable. Restrict every item relation with `acceptedShapeIdentifiers`. Never add price or stock components to a shape: variants have them built in.

Text components are translated and discoverable unless noted.

- Pieces: `seo` (title, description, image); `licence` (basis such as public domain or CC BY, reason, source, source URL, credit).
- **folder** (folder): tagline, intro, seo.
- **title** (product, one film or item):
  - original title, `logline` (up to 110 characters), synopsis, why watch, trivia.
  - `poster`, `key-art`, `stills` (up to 12) images; `clip` videos (a 60–90 s excerpt); `trailer` (a YouTube id, new releases only).
  - `year`, `runtime` (minutes), countries, languages, silent, colour, aspect ratio.
  - `directors`, `writers`, `cast` relations → person; the licence piece; `watched-30d` (popularity) and `rating`; seo.
  - Variants by attribute `offer`: `rent`, `buy`, `stream`. Stream (price 0) for titles included in every plan; rent and buy for the rest; new releases rent or buy only. Variant component `access-hours` (48 for a rental, 0 otherwise). Every variant carries the key art as its image.
- **person** (document): portrait, born, died, roles, bio, seo.
- **collection** (document): tagline, intro, hero images, accent colour, titles (up to 40), seo.
- **plan** (product, "Membership"): tagline, intro. One variant per tier (basic, standard, premium) with plain variant components: tagline, includes, streams, quality, downloads included, rentals discount. Each variant carries the subscription plan `membership`.
- **channel** (product, an add-on): tagline, intro, hero, collections. One variant carrying the plan `channel`.
- Catalogue: `/watch/<title>`, `/people/<person>`, `/collections/<collection>`, `/plans`.
- Topic maps: genre, mood, era, kind (feature, short, serial, documentary, animation).
- Vector vocabularies: `story` (genre [1, 0.7, 0.5], kind [0.4]), `feel` (mood [1, 0.7, 0.5]), `period` (era [1]).
- Pricing: excluding VAT, one price variant per currency, set so prices including VAT land on round price points; one VAT type for digital services. No stock.
- Subscription plan `membership`: Monthly and Yearly periods, each with an initial phase (a 14-day free trial at 0) and a recurring phase; a metered variable `downloads` with graduated tiers (the first 10 free, then a price per download) on the top tier only. Plan `channel`: monthly.
- Order pipelines: Subscriptions (trial, active, paused, past due, cancelled) and Rentals and purchases (paid, delivered, refunded).

## Step 4: my data

Import my products and content with mass operations, mapping my data onto the model: validate each file with `build-mass-operation`, run it with `run-mass-operation` and follow it with `get-mass-operation-status`. Read the operation logs, not just the task status: a task can finish as complete with failed operations, and there is no rollback. Give every upsert a `resourceIdentifier` so a re-run updates instead of duplicating, and chunk large imports. Start with a small batch, check it in the Crystallize App with me, then run the rest.

Publish every imported item in each language: the storefront only sees published versions (in a mass operation, `item/publish` needs real `itemId`s). Import images from URLs with `copyRemoteAsset`, or upload them (presigned upload, then `registerImage`). Renditions are generated in a queue: after a large import, republish once they exist, and have the storefront fall back to the original image URL while `variants` is empty. Before building pages, query Discovery once; if the tenant isn't ignited yet, run `igniteDiscoApi` (with `stacks: opensearch` if we use vector ranking), wait for the task to complete, and allow a few minutes. If I have no data yet, create a small, clearly labelled placeholder set (ten or so products) so we can build the pages, and remind me to replace it.

- The demo's 169 titles come from Wikidata (CC0), Wikimedia Commons and the Internet Archive (public domain), Blender Studio's open movies (CC BY) and NASA; every title keeps its licence and shows a credit.
- Clips were cut with ffmpeg (60–90 s, stereo AAC) and uploaded with `generatePresignedUploadRequest(type: MEDIA)` within the `maxSize` it returns, then written as `{ key, title }` into the `clip` component (no register step); Crystallize transcodes them to HLS and DASH up to 1080p.
- From me: titles and their metadata, the rights, video files (MP4 or MOV), posters and key art, tier definitions and prices, and my taste dimensions.

## Step 5: the storefront

- Next.js (App Router) on Vercel, hls.js for playback. Every action (rent, buy, subscribe, pause) is a server action that also works without JavaScript.
- **Discovery API** for all catalogue reads, facets, plan cards (variants with their subscription plans, periods, prices and metered tiers) and video playlists.
- **Per-profile ranking:** check that ranking is enabled (`__type(name: "RankByInput")`), then rank the whole catalogue once per profile with `rankBy` (one `tasteCosine` term per vocabulary, `from: userTaste`, and a `tieBreaker` from the introspected `TenantRankByTieBreaker` enum) and `context.userTaste`. Build "Because you like horror and eerie" from the profile's top keys matched against the hit's `topicPaths`; keep `explain: true` for a debug flag. Reuse that one ranking for the hero, rows and "For you". Boost recent years with a `fieldBoost` on the year only if it's in `TenantRankByField`. Kids' profiles exclude topics.
- **More like this:** `nearestTo: { vocabulary, like: { itemId }, k }` with a `rankBy` of `tasteCosine from: nearestTo` (0.8) and `from: userTaste` (0.2). An anchor with no vector returns nothing, so check first.
- A profile's taste is its stated keys plus the topics of what it watched, weighted by progress. A household is one Core customer.
- **Item taste (setup):** `upsertVocabulary` (a full replace: send every dimension), then `setItemTaste` per item, vocabulary and language, then rewrite the variant components (taste empties them), then `publishItem` per item and language, then one `igniteDiscoApi(stacks: opensearch)`, polled until complete.
- **Rent and buy (Shop API):** a JWT from `/auth/token` on the server (scopes `cart`, `cart:admin`, `order`); `hydrate` with the household as customer → `place` → `/order` `createFromCart` (the order id is the cart id). Entitlement from Shop `orders(customerIdentifier)`, read on the server with the identifier from the session.
- **Playback gate:** the watch page checks a session claim (tier, state, active until) written at sign-in, after every contract action and by the renewal job. It never reads Core.
- **Subscriptions: the one place this store uses the Core API**, because metered usage can only be tracked there and contracts must live in one store. On the server only, from account pages behind sign-in and from scheduled jobs, never per page view:
  - Create the household's customer first, then `createSubscriptionContract` (`subscriptionPlan { identifier, periodId, periodName }`, renew at = active until = the trial's end, meta for tier, next tier, period, market and period start). Pause and resume (on resume, push the dates forward by the time paused). A tier change is `updateSubscriptionContract { item, recurring }` from the next renewal; monthly ↔ yearly is cancel plus a new contract. `cancelSubscriptionContract(deactivate: false)` ends at the paid period; undo a cancel with `updateSubscriptionContract { status }`, not renew.
  - Metered usage with `trackSubscriptionContractUsage` by the metered variable's `identifier`, with an idempotency key such as `<contract>:<title>:<profile>:<day>`; read `usage(meta.periodStart, now)`, and set `periodStart` at sign-up and at every renewal.
  - Renewals and receipts as orders through the Shop API `/order` `create` (type recurring; a subscription line with the contract id; overage as its own line) in the Subscriptions pipeline, so account pages list them from the Shop API. Make renewals idempotent with meta `renewalOf = <contract>:<renewAt>`; renew adds one period to the previous renew-at date. Add-on channels are separate contracts pointing at the membership.
- Subscription plans, VAT types, order pipelines and markets are created in the PIM API (`pim.crystallize.com/graphql`, which takes the tenant **id**, not the identifier). Price variants are created in the Core API (`createPriceVariant`). Record every generated id (plan period ids, metered-variable ids, pipeline and stage ids) in the setup config.
- Env: `CRYSTALLIZE_TENANT_IDENTIFIER`, `CRYSTALLIZE_ACCESS_TOKEN_ID`, `CRYSTALLIZE_ACCESS_TOKEN_SECRET`, `NEXT_PUBLIC_SITE_URL`.

Build my design, not a demo's: my typefaces, colours and tone, with pages that suit my products. Show me the home page, a category and a product page early, and adjust the design with me before building the rest.

Every page is built for search engines, answer engines and AI agents from the start, not added at the end:
- **SEO:** server-rendered HTML, one `<h1>`, a unique title and description, canonical URLs, `hreflang` per language, a sitemap and `robots.txt`, and clean, translated paths.
- **Structured data:** JSON-LD on every page that has a subject: `Organization` and `WebSite` (with a `SearchAction`) on the home page, `Product` with `Offer` (price, currency, availability) on product pages, `BreadcrumbList` on categories and products, `Article` or `Recipe` on content. Generate it from the same data as the page.
- **GEO, for answer engines and agents:** `/llms.txt` (an H1, a summary, links to every section), `/llms-full.txt`, and a Markdown twin of every page (its URL plus `.md`, or `Accept: text/markdown`), with prices, stock and facts written out in plain sentences.
- **Agents can act, not only read:** register the store's actions (search, add to cart, check availability) with WebMCP (`navigator.modelContext.registerTool`, or annotated forms), and keep the accessibility tree clean: semantic HTML, labelled controls, real buttons and links.
- **Fast and stable:** responsive images from Crystallize, no layout shift (reserve space for images and late content), little client JavaScript. Aim for 100 in every Lighthouse category (Performance, Accessibility, Best Practices, SEO; heavy 3D or video pages may score lower on performance) and pass every Agentic Browsing check.

## Step 6: run it, then ship it

Run it locally and walk me through each feature above with my own data. Fix what I find. Before you call it done, run Lighthouse on the home page, a category and a product page (`npx lighthouse <url> --only-categories=performance,accessibility,best-practices,seo,agentic-browsing`), validate the JSON-LD (https://validator.schema.org), open `/llms.txt` and a page's `.md` twin, and fix what falls short. Deploy only when I ask: set the same environment variables on the host, point my domain, and give me the live URL.

## Watch out for

- Subscription plans live in the PIM API, and their period and metered-variable ids are generated: send them back on every update, or prices and contracts break.
- In Discovery, a plan's initial phase repeats the recurring one: take the trial length from your own config.
- Manage contracts in one place: the Shop API's contracts and Core's barely sync. Public pages (plans, prices) read from Discovery; only the signed-in account touches the contracts.
- Nothing happens by itself at `renewAt`: run renewals yourself in a scheduled job, never on a page view (read usage → price the tiers → skip if an order with `renewalOf` exists → Shop `/order` `create` → `renewSubscriptionContract` → update `periodStart`). Send `renewAt` and `activeUntil` together, never with `activateAt`. Pausing freezes no dates. Updating `meta` replaces all of it.
- A metered variable is `id` on variant pricing and order lines, `identifier` on contracts and usage.
- `setItemTaste` empties variant components on the draft: write them back before publishing. Serialise taste writes per item. `userTaste` has at most one entry per vocabulary, each with `weights` and `magnitude` (the square root of the sum of squared weights; a wrong one fails silently), sent as a variable; `rankBy` needs a `tieBreaker`.
- Publish a title only after its video has finished transcoding, or Discovery keeps an empty playlist. Publish collections after the titles they point to are indexed.
- Send numerics with their unit when creating a product. Publishing a language without content creates items with a missing name.
- Don't invent facts about my business (prices, stock, certifications, delivery promises). Ask, or leave a clearly marked placeholder.

And for every Crystallize store, from the skills:
- **Orders:** create and change them through the Shop API `/order` (`createFromCart`, `create`, `setMeta` with `merge: true`, `addToStage`, `setPayments`). Editing an order in Core adds a duplicate to the Shop API's list. Read a customer's orders with the identifier from the session, `limit: 100`, grouped by `coreId` (keep the newest). Seed order history through `/order` `create`, not Core `registerOrder`. The order id is the cart id; don't call `fulfill` after `createFromCart`.
- **Payments:** create the order from the payment provider's verified webhook, never from the browser, once per cart.
- **Cart meta** goes in `hydrate(input: { meta })`; `hydrate` is the whole cart, so send every line each time.
- **Images:** serve them straight from Crystallize (not through an image optimizer such as `next/image` in its default setup): a WebP `srcset` from the returned `variants` with an accurate `sizes`, falling back to the original URL while renditions are missing. Replace an image by uploading a new one, not with `registerImageRevision`.
- **Ranking (if the store ranks per shopper):** check that `__type(name: "RankByInput")` exists; pass `context` as a variable, with `userTaste` entries of `{ vocabulary, weights, magnitude }` (magnitude = the square root of the sum of squared weights); `tieBreaker` is required; don't combine `sorting` with ranking, and page with `skip` and `limit` inside the rerank window; introspect `TenantRankByField` for field names; leave `context` out when there's no taste; use `explain: true` only for tuning.
- **Bookings (if the store books):** durations are in seconds; the role needs the `bookingPolicies` permission; put the customer on the cart before `bookSkuItem`; every `hydrate` must resend each booked line with its window and unit, or the booking is cancelled; remove a booking by re-hydrating without it.

## Done when

- My tenant has the content model above with my products, prices and images in it.
- The storefront runs on my domain in my brand, and every feature I chose works with my data: we have clicked through each one together.
- Lighthouse scores close to 100 in every category and every Agentic Browsing check passes on the home, category and product pages.
- I know how to add a product, change a price and publish, in the Crystallize App.
