Development guide

Next.js Agentic Commerce Architecture: Catalog to Checkout

By Michael E.Updated Sources checked 14 min

Short answer

Connect a Next.js store to AI shopping tools by putting a thin protocol layer (MCP tools, UCP endpoints, or both) in route handlers, behind which typed adapters wrap each backend system: catalog, inventory, pricing, policy, and checkout. Cache catalog content aggressively, never cache stock or price decisions, recheck both live before any cart or order, and trace every tool call end to end.

Key takeaways

  • Check what your commerce backend already exposes first: a Shopify backend, for example, has its own Storefront Catalog MCP endpoint.
  • Keep protocols at the edge and business rules in adapters, so adding UCP next to MCP does not duplicate pricing or stock logic.
  • Cache what describes products; fetch live what decides a purchase.
  • Tools that prepare carts should return drafts for buyer confirmation, never place orders silently.
  • Every tool response should carry the source records it relied on, so answers can be traced and audited.

How do I connect a Next.js store to AI shopping tools?

Start by finding out what your commerce backend already provides, then add only the missing layer. A Next.js storefront is usually a headless frontend on top of a commerce backend, and several backends now expose agent-facing catalog and checkout surfaces of their own.

Native first: what to check before building
BackendWhat may already existWhat a Next.js team may still build
Shopify (headless)Shopify Catalog syndication to agentic channels, and a Storefront Catalog MCP endpoint at https://{storedomain}/api/ucp/mcp whose tools conform to UCPCustom tools for data Shopify does not model (fitment, configurators), assistant UI, observability
Other SaaS backendsPlatform feeds, MCP or agent features (check current docs, which change often)Adapters for ERP/PIM data, custom tools, protocol endpoints the platform does not offer
Custom backendNothing agent-specificFeed export, MCP tools, and, if eligible, UCP or ACP checkout endpoints
MCP
The Model Context Protocol, an open protocol for exposing tools and data to AI applications through a server.
UCP
Google's Universal Commerce Protocol, an open standard for catalog, cart, checkout, and order capabilities between platforms and businesses.
Adapter
A module that wraps one backend system behind a typed interface, so the rest of the app never calls that system directly.
Route handler
A Next.js App Router file (route.ts) that handles HTTP requests for a path, used here for protocol endpoints.

For the broad picture of MCP in ecommerce, start with MCP for ecommerce; for how UCP and ACP differ, see ACP vs UCP vs MCP. The headless commerce platform page explains what we typically build on custom stacks.

What should a Next.js agentic commerce architecture look like?

Four layers: an edge that verifies who is calling, a protocol layer that speaks MCP or UCP, a domain layer of typed adapters that owns business rules, and the systems of record behind them. The storefront pages and the protocol endpoints share the same adapters.

Reference architecture (text diagram).
  AI platforms / agents              Browsers
  (MCP clients, UCP platforms)       (shoppers, browser agents)
          |                                  |
  +-------v----------------------------------v--------+
  | EDGE: CDN / WAF / bot management                    |
  |  verify mTLS, signatures, OAuth; rate-limit per     |
  |  session/token; no JS challenges on API paths       |
  +-------+----------------------------------+--------+
          |                                  |
  +-------v-----------------+   +------------v--------+
  | PROTOCOL LAYER          |   | STOREFRONT          |
  | app/api/mcp/route.ts    |   | app/(shop)/...      |
  | app/.well-known/ucp/    |   | Server Components   |
  | app/api/ucp/checkout/   |   | 'use cache' for     |
  | schema validation, auth |   |  catalog content    |
  +-------+-----------------+   +------------+--------+
          |                                  |
  +-------v----------------------------------v--------+
  | DOMAIN LAYER (lib/commerce)                         |
  |  CatalogAdapter   InventoryAdapter  PricingAdapter  |
  |  PolicyAdapter    CartAdapter       CheckoutAdapter |
  |  rules: fitment, shipping limits, quantity limits   |
  +--+-----------+-----------+-----------+-------------+
     |           |           |           |
   PIM/        WMS/OMS     ERP/price    PSP, tax,
   commerce    (stock)     engine       shipping
   backend

  Cross-cutting: trace id per request -> logs, metrics, tool-call audit
  • Edge: identity and abuse control. Different callers need different rules; see why AI agents get blocked by your firewall.
  • Protocol layer: translation only. It validates input against the protocol schema, maps it to domain calls, and maps results back. No pricing or stock logic lives here.
  • Domain layer: the business rules and the only code that talks to backends. Both the storefront and the protocol layer call it.
  • Systems of record: unchanged. The architecture adds no new source of truth.

Why separate adapter boundaries for catalog, inventory, pricing, and checkout?

Because each system has a different freshness requirement, failure mode, and owner. Separate adapters let you cache the catalog while calling inventory live, swap a pricing engine without touching protocol code, and test each failure on its own.

Illustrative sketch: domain interfaces (lib/commerce/types.ts). Every result carries the source records it used.
export interface Fact { source: string; text: string }   // e.g. 'inventory/SKU-123'
export type Result<T> =
  | { ok: true; data: T; facts: Fact[] }
  | { ok: false; error: { code: string; message: string }; facts: Fact[] };

export interface CatalogAdapter {
  search(q: { query: string; category?: string; limit?: number }): Promise<Result<SearchHit[]>>;
  getProduct(id: string): Promise<Result<ProductView>>;            // no stock in here
  checkCompatibility(id: string, model: string): Promise<Result<Compat>>;
}
export interface InventoryAdapter {
  getSellable(sku: string, locationId?: string): Promise<Result<{ available: number }>>;
}
export interface PricingAdapter {
  quote(lines: Line[], buyer?: BuyerRef): Promise<Result<PricedLine[]>>; // live, buyer-aware
}
export interface CartAdapter {
  prepareDraft(lines: Line[], shipTo?: ShipTo): Promise<Result<CartDraft>>; // never places an order
}

This is the same contract our catalog-to-cart demonstration uses. Its six tools are search_catalog, get_product, check_compatibility, check_inventory, get_policy, and prepare_cart. get_product deliberately returns no stock, so the only way to state availability is check_inventory. prepare_cart revalidates stock and shipping rules and returns a draft with status requires_customer_confirmation; it cannot place an order or take payment. Every tool returns the source records it used, which is what lets an answer cite them. The demo runs a scripted planner with no language model, on synthetic data, so it shows the contract rather than assistant quality.

Where should an MCP server live in a Next.js app?

In a route handler, such as app/api/mcp/route.ts, that only translates between MCP and the domain layer. Keep it on the Node.js runtime if your adapters need database drivers, and keep each tool small and typed.

Illustrative sketch: protocol layer delegating to the domain layer. Use an MCP SDK in practice; authentication is omitted here.
// app/api/mcp/route.ts
import { commerce } from '@/lib/commerce';   // wires adapters to real backends
import { traced } from '@/lib/observability';

const tools = {
  search_catalog: (i: SearchIn) => commerce.catalog.search(i),
  get_product:    (i: { productId: string }) => commerce.catalog.getProduct(i.productId),
  check_inventory:(i: { sku: string }) => commerce.inventory.getSellable(i.sku),
  prepare_cart:   (i: CartIn) => commerce.cart.prepareDraft(i.lines, i.shipTo),
} as const;

export async function POST(req: Request) {
  const msg = await req.json();               // JSON-RPC 2.0 'tools/call'
  const name = msg.params?.name as keyof typeof tools;
  if (!tools[name]) return rpcError(msg.id, -32602, 'unknown tool');
  const input = validate(name, msg.params.arguments);   // zod/JSON Schema per tool
  if (!input.ok) return rpcError(msg.id, -32602, input.message);
  const result = await traced(`tool.${name}`, req, () => tools[name](input.value as never));
  return Response.json({ jsonrpc: '2.0', id: msg.id, result: toMcpContent(result) });
}

A UCP checkout implementation follows the same pattern with REST routes (for example create, update, complete, and cancel checkout) calling the same CheckoutAdapter. Google's UCP FAQ says REST is the default for its Native Checkout path, and that MCP transport for checkout is in early access with separate onboarding, so do not assume one transport covers every surface. Building the MCP server itself is covered step by step in build an ecommerce MCP server with TypeScript.

What should be cached in an agentic commerce stack?

Cache what describes a product; fetch live what decides a purchase. Titles, descriptions, attributes, images, fitment tables, and policy text change slowly and can be cached with tag-based revalidation. Stock, price for a specific buyer, shipping eligibility, and tax must be read at decision time.

DataCache?How (Next.js with Cache Components)Invalidate on
Product content and attributesYes'use cache' with cacheLife and cacheTag('product:<id>')PIM or backend product-update webhook calling revalidateTag
Category listings, search facetsYes, short'use cache' with a short cacheLife profileCatalog publish events
Fitment and compatibility tablesYesTagged cache per table versionFitment data release
Policy text (returns, shipping rules)YesTagged cache with the policy IDPolicy change
Sellable stockNoUncached call in the request pathn/a (read live)
Buyer-specific or B2B priceNoUncached, buyer-scoped calln/a
Shipping options, taxNoUncached calls to the shipping and tax adaptersn/a
UCP business profile (/.well-known/ucp)YesStatic or long-lived. Separately, Google's network guide says not to cache the platform's UCP-Agent profile or signing keys you fetch for longer than max-age=86400Deploy of new capabilities
Illustrative sketch: cached catalog read, uncached stock read (Next.js Cache Components).
// lib/commerce/catalog.ts
import { cacheLife, cacheTag } from 'next/cache';

export async function getProductView(id: string) {
  'use cache'
  cacheLife('hours');
  cacheTag(`product:${id}`);
  return backend.products.get(id);   // content only, no stock
}

// lib/commerce/inventory.ts  (no cache directive: runs per request)
export async function getSellable(sku: string) {
  return oms.sellable(sku);           // live
}

// app/api/hooks/product-updated/route.ts
import { revalidateTag } from 'next/cache';
export async function POST(req: Request) {
  const { productId } = await verifyAndParse(req);
  // { expire: 0 }: next request refetches instead of serving stale content.
  // 'max' (Next.js's recommended default) serves stale while revalidating.
  revalidateTag(`product:${productId}`, { expire: 0 });
  return new Response(null, { status: 204 });
}

The Next.js caching docs also note that, with Partial Prerendering, some bots and crawlers are detected by user agent and rendered dynamically at request time, so data sources used during prerendering must also be available at request time or those bots receive errors. Test product pages with crawler user agents as part of your release checks.

How do live price and stock checks work before a cart or order?

Every action that commits the buyer to something rechecks price and stock live, even if the agent read them a minute earlier. The agent's earlier read is context; the live check is the decision.

Illustrative sketch: draft cart with live revalidation. Mirrors the demo's prepare_cart behavior.
export async function prepareDraft(lines: Line[], shipTo?: ShipTo): Promise<Result<CartDraft>> {
  const facts: Fact[] = [];
  const accepted: PricedLine[] = [];
  const rejected: { sku: string; reason: string }[] = [];
  const [stock, prices] = await Promise.all([
    inventory.getSellableMany(lines.map((l) => l.sku)),   // live
    pricing.quote(lines),                                   // live
  ]);
  for (const l of lines) {
    const s = stock[l.sku];
    if (!s || s.available < l.qty) { rejected.push({ sku: l.sku, reason: 'INSUFFICIENT_STOCK' }); continue; }
    const rule = await policy.shippingRule(l.sku, shipTo);
    if (!rule.allowed) { rejected.push({ sku: l.sku, reason: rule.reason }); continue; }
    accepted.push(prices[l.sku]);
    facts.push({ source: `inventory/${l.sku}`, text: `${s.available} sellable at check time` });
  }
  return { ok: true, facts, data: { status: 'requires_customer_confirmation', lines: accepted, rejected } };
}

Checkout endpoints repeat the same checks at completion, because stock can sell out between draft and order. The agentic checkout testing guide includes the stock-race and price-integrity tests for this, and inventory sync with webhooks and reconciliation covers keeping the inventory adapter's source accurate.

What observability does an agentic commerce stack need?

A trace ID on every inbound protocol request, propagated to every adapter call, plus a structured audit record of each tool call. When a buyer says an assistant told them something wrong, you need to replay exactly which tool returned what, from which source record.

SignalWhat to recordWhy
Tool-call audit logTool name, validated input, result code, facts (source IDs), latency, caller identity, trace IDReconstruct any answer or cart; spot tools that error often
Adapter metricsLatency and error rate per backend (catalog, OMS, pricing, tax, PSP)Find which system makes agents slow or wrong
Cache metricsHit rate and revalidation events per tagConfirm content caching works and live data is never cached
Outcome countersDrafts created, drafts rejected by reason, checkouts completed, out-of-stock at completionSee where purchases fail
Edge logsVerified identity, rule matched, action takenSeparate blocked agents from application errors
Illustrative sketch: wrapping tool calls with a trace and an audit record. Do not log payment data or unnecessary personal data.
export async function traced<T>(name: string, req: Request, fn: () => Promise<Result<T>>) {
  const traceId = req.headers.get('request-id') ?? crypto.randomUUID();
  const started = performance.now();
  const result = await withSpan(name, { traceId }, fn);   // OpenTelemetry or similar
  audit.write({
    traceId, tool: name, ok: result.ok,
    error: result.ok ? undefined : result.error.code,
    sources: result.facts.map((f) => f.source),
    ms: Math.round(performance.now() - started),
    caller: callerIdentity(req),                          // from verified auth, not headers alone
  });
  return result;
}

In what order should a Next.js team build this?

  1. 1

    Inventory native capabilities

    List what your backend and channels already expose: catalog syndication, feeds, MCP endpoints, checkout options. Do not rebuild them.

  2. 2

    Define the domain interfaces

    Write the adapter interfaces and the Result and Fact types first, then implement them against staging backends.

  3. 3

    Ship read-only tools

    Search, product detail, compatibility, live stock, and policy. These carry little risk and show data gaps quickly.

  4. 4

    Add draft carts

    A tool that returns a draft for buyer confirmation, with live revalidation.

  5. 5

    Add observability before traffic

    Tracing, the audit log, and the outcome counters.

  6. 6

    Add checkout only if eligible

    UCP or ACP checkout endpoints, after confirming the platform eligibility and onboarding path, and after the full checkout test plan passes.

If the store's real problem is the browser path, where agents visit pages and struggle with forms, WebMCP tools in the storefront may matter more than a server; see our WebMCP integration service. For the stock and price adapters specifically, see inventory and pricing API integration.

Frequently asked questions

Do I need Next.js for agentic commerce?

No. The architecture is framework-neutral: an edge, a protocol layer, typed adapters, and systems of record. Next.js route handlers and its caching model are one convenient way to build it, and our own demonstration runs on SolidStart.

Should the MCP server be a separate service or part of the Next.js app?

Either works. Inside the app is simpler when the storefront and tools share adapters and deploy together. A separate service makes sense when other channels also use the tools, when you need different scaling, or when the team that owns the backend owns the tools.

Can I cache stock for a few seconds to reduce backend load?

For display on listing pages, a very short cache can be reasonable if you label availability as approximate. For any tool response an agent will treat as fact, and for cart and checkout, read stock live.

Our backend is Shopify. Do we need our own catalog MCP server?

Often not for basic catalog search. Shopify documents a Storefront Catalog MCP endpoint per store with search, lookup, and product tools that conform to UCP. Custom tools make sense for data Shopify does not model, such as fitment or configuration rules.

Should the assistant be able to place orders?

Not silently. Tools should return drafts that the buyer confirms, and order placement should go through a checkout flow with explicit consent, such as a protocol checkout or a handoff to your checkout page.

How do we keep tool answers from inventing product specs?

Return only attributes that exist in the catalog, return typed errors for unknown models or missing specs, and include source records in every response. The demonstration escalates instead of answering when a spec is missing.

Does this architecture make AI platforms recommend our products?

No. It makes your catalog, stock, and cart data reliable and callable. Whether a platform surfaces or recommends products depends on its own eligibility rules and ranking.

Building on a headless or custom stack?

Tell us your frontend, commerce backend, PIM/ERP, and which AI channels matter. We start from what your backend already exposes.

Sources

  1. Shopify: Storefront Catalog MCP
  2. Google: UCP FAQ
  3. Google: UCP network and WAF configuration
  4. UCP specification overview
  5. Next.js: Caching (Cache Components)
  6. Next.js: revalidateTag
  7. MCP security best practices
  8. Agent Commerce Optimization: catalog-to-cart demonstration (synthetic data)

Platform capabilities, eligibility, and specifications change. Sources were checked on 2026-11-29; confirm the current primary documentation before scoping an implementation. See our editorial policy and methodology.