docs
/
Client Integration

Server proxy

A concrete request-owned Next.js pricing route, and the boundaries of the shipped Next.js, Remix, and hosted renderer gateways.

Your server accepts a small application request, obtains the visitor session, and calls AppEngine with application identity plus optional customer identity. Define the public method and path deliberately; a route that can attach your credentials to arbitrary upstream URLs exposes more authority than the UI displays.

The shipped Next.js example has a catch-all /api/[...slug] with prefix checks. Remix instead has POST /api/price, implemented by an action. The larger base-app hosted renderer has its own gateway and session helpers. These are distinct implementations; functions from base-app are not exports of @appmint/js-client.

A pricing route with the source SDK

Install the SDK and create clientForRequest from the TypeScript reference. For Next.js, put this in app/api/price/route.ts. This route deliberately accepts product-only carts; extend its schema explicitly for variants, rentals, or other features.

import { NextRequest, NextResponse } from 'next/server';
import { AppmintError, AppmintNetworkError } from '@appmint/js-client';
import { clientForRequest } from '@/lib/appmint.server';

export async function POST(request: NextRequest) {
  const expectedOrigin = process.env.APP_ORIGIN;
  if (!expectedOrigin) {
    return NextResponse.json({ error: 'Server origin is not configured' }, { status: 503 });
  }
  if (request.headers.get('origin') !== expectedOrigin) {
    return NextResponse.json({ error: 'Origin not allowed' }, { status: 403 });
  }
  if (!request.headers.get('content-type')?.startsWith('application/json')) {
    return NextResponse.json({ error: 'Expected JSON' }, { status: 415 });
  }
  let input: any;
  try { input = await request.json(); }
  catch { return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 }); }

  const rows = input?.productItems;
  if (!Array.isArray(rows) || rows.length < 1 || rows.length > 100 ||
      rows.some((row: any) => !row || typeof row.sku !== 'string' ||
        !row.sku.trim() || !Number.isInteger(row.quantity) ||
        row.quantity < 1 || row.quantity > 100)) {
    return NextResponse.json({ error: 'Invalid cart lines' }, { status: 400 });
  }
  const rawAddress = input.shippingAddress;
  if (!rawAddress || typeof rawAddress !== 'object' || Array.isArray(rawAddress)) {
    return NextResponse.json({ error: 'Shipping address is required' }, { status: 400 });
  }
  const shippingAddress: Record<string, string> = {};
  for (const key of ['name', 'street1', 'street2', 'city', 'state', 'zip', 'country', 'phone']) {
    const value = rawAddress[key];
    if (value !== undefined && (typeof value !== 'string' || value.length > 200)) {
      return NextResponse.json({ error: 'Invalid address field' }, { status: 400 });
    }
    if (value !== undefined) shippingAddress[key] = value;
  }
  if (input.couponCode !== undefined && typeof input.couponCode !== 'string') {
    return NextResponse.json({ error: 'Invalid coupon' }, { status: 400 });
  }

  try {
    const client = clientForRequest(request.cookies.get('appmint_token')?.value ?? null);
    // Resolve every SKU first. A price alone is not proof of a sellable product.
    const products = await Promise.all(rows.map((row: any) => client.products.get(row.sku)));
    if (products.some((row) => !row?.data?.sku || row.data.status !== 'active')) {
      return NextResponse.json({ error: 'A product is unavailable' }, { status: 409 });
    }
    const summary = await client.cart.price({
      productItems: rows.map((row: any, index: number) => ({
        sku: products[index].data.sku, quantity: row.quantity, itemType: 'product',
      })),
      shippingAddress,
      couponCode: input.couponCode || undefined,
    });
    return NextResponse.json(summary, { headers: { 'Cache-Control': 'no-store' } });
  } catch (error) {
    if (error instanceof AppmintNetworkError) {
      return NextResponse.json({ error: 'Pricing is temporarily unavailable' }, { status: 503 });
    }
    if (error instanceof AppmintError) {
      return NextResponse.json({ error: error.message, code: error.code }, { status: error.status });
    }
    return NextResponse.json({ error: 'Pricing failed' }, { status: 500 });
  }
}

Set APP_ORIGIN=http://localhost:4100 for the local example and your exact HTTPS origin in deployment. Cookie creation belongs in your login/session routes; this pricing route does not sign anyone in. Product preflight reduces bad inputs but is not an atomic stock or price guarantee. Checkout still needs its own authoritative checks.

The browser calls only this route and parses the response once:

const response = await fetch('/api/price', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  credentials: 'same-origin',
  body: JSON.stringify({
    productItems: [{ sku: selectedSku, quantity: 1 }],
    shippingAddress: destination,
    couponCode: coupon || undefined,
  }),
});
const summary = await response.json();
if (!response.ok) throw new Error(summary.error ?? 'Pricing failed');
// Render summary.total. Also handle summary.valid === false.

When adapting the example catch-all

nextjs-store/app/api/[...slug]/route.ts currently permits storefront/, profile/customer/, profile/magic-link, affiliate/public/, client/, shipping/, and notice/. Those prefixes include more than the demo cart needs. A prefix match is not endpoint authorization, and profile/magic-link is not an exact match. For deployment, replace broad prefixes with reviewed method/path pairs or dedicated routes; retain backend authorization for every operation. Never accept an upstream host, application credentials, or trusted tenant from the browser.

The example preserves query strings, passes appmint_token as a per-call argument, and forwards upstream HTTP errors. It reads JSON only, discards DELETE bodies, returns JSON on success, and does not forward every upstream header. It is not a universal upload/download proxy. Handle multipart, streaming, HTML, and binary response types in routes designed for those contracts.

The SDK's network exception has status 0; map it to a valid HTTP status such as 503 before constructing a response. Forward meaningful upstream 400/401/403/404/409 statuses without turning each into 500. Do not return internal network exception text to visitors.

Session and isolation checks

Run two authenticated requests concurrently, followed by an anonymous request. Check upstream customer headers with a mock transport and verify private data against two disposable customers. Reject a wrong-origin POST and a forbidden path without making any upstream request. Submit malformed JSON, negative quantity, an unknown SKU, and an extra price field: your route should reject invalid input or strip unsupported fields, and never trust a browser total.

Server components and Remix loaders already run on the server. They should call the server transport directly with request-specific identity; they do not need to make an HTTP request back through their own proxy.