Key takeaways
-
- Thor Commerce enforces a strict architectural boundary by separating administrative operations from buyer-facing catalog discovery, carts, and checkout via distinct GraphQL APIs.
- The official reference storefront pairs Next.js 16, React 19, TypeScript, and Server Actions to guarantee type safety and keep sensitive API tokens server-side.
- Autonomous coding agents such as Claude Code and Cursor require contract-driven boundaries, leveraging AGENTS.md and live GraphQL schemas to prevent business logic hallucinations.
- Cart state, pricing, tax, and discount rules must remain server-calculated within Thor’s commerce context, avoiding client-side recalculation errors.
Building a production-ready Thor Commerce storefront with artificial intelligence requires constraining coding agents within typed API contracts rather than allowing models to guess commerce logic. Thor Commerce delivers a headless architecture that divides operations between an administrative control plane and a buyer-facing Storefront API. By combining Thor’s open-source Next.js 16 reference storefront with modern coding agents such as Claude Code, Cursor, or Codex, engineering teams can customize user interfaces, market-aware pricing, and purchasing journeys rapidly. Rather than asking an LLM to invent checkout calculations or cart state, developers bind the agent to GraphQL schemas, typed documents, and server-side authentication boundaries, ensuring strict data integrity and reproducible deployment.
Historically, engineering a custom digital commerce experience required choosing between restrictive monolithic SaaS templates or investing substantial capital to build catalog, inventory, pricing, checkout, and account logic from the ground up. As documented across Thor Commerce, headless architecture resolves this dilemma by decoupling backend operations from frontend presentation. The commerce engine governs inventory thresholds, market currencies, tiered discounts, and tax computation, while ordinary web application code renders the customer touchpoint. When paired with generative software engineering agents, this decoupled pattern provides the explicit structure that autonomous coding tools need to operate reliably without introducing state corruption or security oversights.
Architectural Separation Between Admin and Storefront Operations
Autonomous AI agents frequently stumble when given ambiguous system boundaries. In complex enterprise ecommerce environments, allowing an agent to manage business logic without constraints invariably leads to hallucinated data models, broken calculations, and severe security flaws. Thor Commerce prevents these pitfalls by establishing a bifurcated API design exposed entirely through typed GraphQL endpoints:
- The Admin API: Serves as the trusted back-office control plane. It manages server-side administrative workflows including catalog taxonomy, pricing tier matrices, inventory allocations, channel configurations, customer accounts, and order fulfillment. Access requires high-privilege credentials that must never be exposed to frontend code or client bundles.
- The Storefront API: Powers buyer-facing interactions including product discovery, search filtering, localized price resolution, session carts, checkout mutation sequences, and authenticated customer self-service portals. Storefront requests operate in a restricted buyer context where permissions are scoped strictly to public shopping interactions.
As highlighted in the engineering analysis on how to build a custom ecommerce store with Thor Commerce and AI, this architectural separation eliminates the need for coding agents to invent calculations for complex business logic. Because both APIs are defined via strict GraphQL contracts, developers and AI agents can query the precise fields required for a specific component without carrying superfluous payload overhead.
Furthermore, Thor Commerce natively resolves commerce state in context. A single catalog entity can maintain distinct purchase availability, pricing schedules, and currency denominations across multiple storefront instances, geographic jurisdictions, customer groups, and wholesale channels. This unified data model allows enterprises to operate direct-to-consumer (DTC) and business-to-business (B2B) portals simultaneously without synchronizing duplicate product databases.
Repository Setup and Server-Side Credential Isolation
To establish a functional development environment, engineering teams begin with the official open-source reference implementation available on GitHub. The foundation is constructed upon Next.js 16, React 19, TypeScript, React Server Components (RSC), and Server Actions, providing an optimal environment for server-rendered commerce logic.
Before launching local development, ensure your local toolchain meets the minimum platform prerequisites:
- Node.js version 20.9 or newer
- pnpm package manager
- Git version control
- An active Thor Commerce project with provisioned Storefront API access
- A configured store containing at least one published, active product variant with assigned pricing and inventory
- A local repository-aware coding agent such as Claude Code, Cursor, or Codex
Initialize the repository locally by cloning the reference codebase and installing project dependencies:
git clone https://github.com/thor-commerce/next-thor-storefront.git
cd next-thor-storefront
pnpm install
Environment configuration requires strict credential isolation. Duplicate the example environment file and populate project-specific secrets:
cp .env.example .env
Configure the following critical environment variables within .env:
THOR_PROJECT = "your-project-slug"
THOR_STOREFRONT_API_KEY = "your-storefront-token"
BETTER_AUTH_SECRET = "generate-a-new-secret"
BETTER_AUTH_URL = "http://localhost:3000"
NEXT_SERVER_ACTIONS_ENCRYPTION_KEY = "generate-a-new-persistent-key"
Security discipline is paramount when configuring coding agents. The project slug uniquely identifies your Thor organization space, while the storefront token is passed across server-side requests via the X-Thor-Storefront-Token HTTP header. Under no circumstances should developers assign a NEXT_PUBLIC_ prefix to this token or expose Admin API keys within the client storefront environment. Private keys must never be committed to source control or pasted directly into conversational AI prompts. In modern infrastructure, relying on code obscurity or hidden client scripts invites immediate exposure; as detailed in TechNode HQ’s analysis of why security through obscurity is dead in enterprise AI environments, programmatic guardrails and strict server-side token isolation must enforce data boundaries instead.
Following environment setup, configure market routing in src/lib/thorcommerce/config.ts. Developers must map real country codes, default locales, currency bindings, and Thor store identifiers according to the official Thor Next.js storefront guide. Maintaining consistent market context ensures catalog listings match corresponding checkout sessions.
Typed GraphQL Contracts and Schema Synchronization
A primary failure mode when deploying AI agents in web development is the generation of stale or invented API queries. Thor Commerce neutralizes this risk through automated schema inspection and code generation. The reference storefront includes preconfigured GraphQL codegen tooling that compiles raw .graphql document definitions into fully typed TypeScript query operations and mutation hooks.
To inspect the remote API and regenerate static types, execute the codegen pipeline:
pnpm codegen
Once type generation finishes without errors, launch the Next.js local development server:
pnpm dev
Navigating to http://localhost:3000 triggers Next.js edge middleware, which automatically inspects request headers and redirects the user to a localized, country-prefixed route such as /dk or /de. The application resolves products, variant options, and localized pricing corresponding to the store configuration defined for that market.
If the catalog renders an empty state upon initial boot, engineering teams should avoid modifying UI components or injecting mock data. Instead, prompt the AI agent with a strict diagnostic mandate referencing official Thor Commerce documentation:
The storefront returns no catalog products for route /dk.
Diagnose the failure layer without changing UI data or schema files.
Verify the project slug, Storefront API token, store identifier,
country code, currency, price channel, publication availability window,
and inventory status. Report the exact failing layer with evidence.
This structured diagnostic prompt prevents coding agents from masking systemic configuration errors behind brittle frontend fallbacks, forcing the model to verify data layer integrity before touching visual code.
Guardrailed Agent Workflows and Prompt Boundaries

To maximize developer productivity without compromising system stability, software teams must establish standardized operational boundaries for coding agents. Rather than instructing an LLM to build an ecommerce feature without limits, engineers should structure tasks around Thor’s built-in developer context files.
Thor Commerce provides explicit context discovery files that guide autonomous tools. The root repository contains an AGENTS.md file alongside domain-specific Storefront API skills. Furthermore, the platform publishes an llms.txt context index linking directly to clean Markdown documentation. These files inform agents about architectural conventions, request pipelines, and mutation lifecycles prior to code generation.
When extending the storefront, adhere to the repeatable five-step prompt loop outlined in Thor’s guide on how to build with an AI agent:
- State the Desired Outcome: Articulate the exact buyer or administrative behavior required, such as displaying a structured technical specification table on product pages.
- Name the Exact Surface: Explicitly designate whether the modification resides within the Storefront presentation layer, an Admin API integration, or an embedded dashboard extension.
- Point to Authoritative Documentation: Command the agent to read
AGENTS.md, relevant GraphQL operation definitions, and official Thor schema guides before modifying files. - Set Rigid Operational Boundaries: Explicitly forbid hallucinated database IDs, unverified schema fields, hardcoded credentials, and synthetic mock datasets.
- Mandate Verification Proof: Require the agent to provide a detailed list of modified files, terminal execution traces (such as
pnpm codegenandpnpm build), observed visual states, and untested edge dependencies.
For example, when introducing custom product specifications, developers can utilize Thor’s typed metafield system. Instead of adding arbitrary JSON properties to a React component, instruct the agent to inspect the Admin and Storefront GraphQL schemas, define the typed metafield definition, add the query field to src/lib/thorcommerce/storefront/queries/products.graphql, execute pnpm codegen, and render the resulting typed property accessibly.
Cart Persistence, Contextual Pricing, and Order Validation
The cart and checkout sequence represents the most critical path in any digital commerce system. A frequent defect in AI-generated commerce applications is the recalculation of order totals, discounts, shipping fees, or sales taxes directly inside client-side JavaScript. This practice exposes businesses to severe pricing tampering, client-server state divergence, and checkout abandonment.
In Thor Commerce, all commerce calculations are strictly server-authoritative. When a buyer selects a product variant, applies a promotional code, or selects a freight option, the storefront dispatches a GraphQL mutation to the Storefront API via Next.js Server Actions. Thor calculates taxes, line-item discounts, inventory reservations, and gross totals against the active market context. The client application merely renders the verified cart object returned by the server.
To ensure system resilience, AI agents must execute comprehensive end-to-end testing across both successful purchase flows and common operational failure paths:
- Inventory Thresholds: Attempting to purchase quantities exceeding verified stock must trigger clear error boundaries rather than unhandled promise rejections.
- Cart Expiration: Stale browser sessions must cleanly reconcile updated variant pricing or flag discontinued items without corrupting the session cookie.
- Promotion Boundaries: Expired or inapplicable discount codes must return structured validation errors while preserving existing cart line items.
- Payment State Transitions: Canceled Stripe intents or declined transactions must leave the customer’s cart intact and provide clear recovery prompts.
Following local testing, the reference storefront provides preconfigured OpenNext and Wrangler scripts optimized for Cloudflare Workers, incorporating R2-backed incremental cache handlers. Platform engineers must verify that edge deployment variables match target production environments, particularly adapting country detection middleware to inspect the CF-IPCountry header accurately.
Architecture Comparison: AI Autonomous Guessing vs. Contract-Constrained Development
The operational divide between unconstrained AI generation and contract-governed engineering illustrates why typed architectures are necessary for modern software delivery. The following table summarizes key architectural differences:
| Operational Dimension | Unconstrained AI Generation | Contract-Constrained Development |
|---|---|---|
| Schema Authority | LLM guesses REST endpoints, payload shapes, and field names. | Strictly bound to live GraphQL schemas via automated type generation. |
| Pricing and Totals | Calculated client-side via JavaScript functions, vulnerable to tampering. | Authoritatively evaluated by Thor’s backend engine within contextual market rules. |
| Credential Management | Tokens frequently leaked in client bundles or embedded in prompts. | Tokens isolated to server runtime via X-Thor-Storefront-Token headers. |
| Multi-Market Routing | Hardcoded currencies and localized routes requiring manual refactoring. | Dynamic edge middleware resolving store identifiers, currencies, and tax rules. |
| Developer Verification | Visual spot-checks that overlook silent state synchronization errors. | Automated static typing, schema validation, linting, and end-to-end checkout verification. |
Implementation checklist
Before releasing a custom Thor Commerce storefront to production traffic, platform teams and engineering leaders should verify the following operational requirements:
- Contract Alignment: Execute
pnpm codegento verify that all storefront queries and mutation documents perfectly match the target Thor project schema without missing fields or unhandled nullability types. - Credential Isolation: Confirm that
THOR_STOREFRONT_API_KEYand authentication secrets are stored strictly within secure server environment stores and that no private tokens carry client-exposed prefixes. - Contextual Market Verification: Validate that country-prefixed routes (e.g.,
/dk,/de) accurately map to corresponding Thor store IDs, currencies, price channels, and tax matrices. - Authoritative Cart Mutations: Confirm that all cart modifications, promotional discounts, and shipping additions reflect backend-calculated cart states without client-side total recalculation.
- Edge Middleware Readiness: Review Next.js middleware routing in
src/middleware.tsto ensure geographic geolocation headers (such asCF-IPCountryon Cloudflare) correctly resolve target market fallbacks. - Failure Path Resilience: Verify that out-of-stock items, expired customer sessions, declined payments, and invalid discount codes render accessible, actionable recovery feedback.
- Build and Lint Verification: Execute
pnpm lintandpnpm buildlocally and in continuous integration pipelines to guarantee zero TypeScript or compilation regressions prior to deployment.
Sources
- How to Build a Custom Ecommerce Store with Thor Commerce and AI – DEV Community
- GitHub – thor-commerce/next-thor-storefront: Next.js 16 headless commerce storefront for Thor Commerce with typed GraphQL, cart, checkout, Stripe, auth, and multi-market routing.
- Headless Commerce Platform for B2B and DTC
- Thor Commerce Docs
- Thor Commerce
- Build with an AI agent
- Build with the Next.js storefront



