Skip to content

Dukachap / Developer guide / Practical tutorial

Build an eatery storefront with React and TypeScript

Built around a real store called Kisumu Kitchen. The menu and cart screens were clicked through in a browser, and the account, payment and table-request steps were run with curl against a local DukaChap API. The guide uses the issued Storefront endpoint: its URL shape, headers and permissions were checked against the DukaChap source and with read-only requests to a local endpoint (17 November 2026), and steps that were not run are marked. Where something differed from what you might expect, we say so.

What we are building

A customer browses three dishes, adds vegetable rice to a cart, signs up, and pays through an M-Pesa prompt. Another customer requests a table for Friday evening and verifies their email. Someone asks a menu guide, in English or Kiswahili, what to order with a small budget. Every one of those requests is shown below exactly as it ran, with the real response that came back.

You write the React interface; DukaChap runs the business services. You will not create an application server, a database, a payment callback, an email sender or an AI integration. In development, a small Vite proxy attaches your DukaChap credentials to outgoing requests so they never reach the browser; in production the same job is done by a Netlify build plugin.

Customer's browser → React (Vite dev proxy, or Netlify in production) → Storefront endpoint → DukaChap
                                                                     ├─ catalogue, stock and pricing
                                                                     ├─ carts, accounts and orders
                                                                     ├─ M-Pesa and payment confirmation
                                                                     ├─ verified forms and metaobjects
                                                                     └─ AI text generation
Eatery staff → DukaChap staff API → table bookings and deliveries

Two things only staff can do. A submitted table request needs staff confirmation — the public form stores an email-verified entry, it does not reserve a table. And turning a paid order into a delivery or pickup needs the staff fulfilment API. Both are real, working DukaChap endpoints; this guide shows the exact requests, but you call them from a staff API client, not from the public React app, so section 11 shows curl, not a screen.

This guide assumes basic React, TypeScript and terminal familiarity. Start with React's Learn React guide first if components, props and hooks are new to you, then come back here to connect a real store.

Before you start

  • Node.js 20+ and npm, Git, a code editor and a modern browser. This guide was built and run with Vite 8, React 19 and TypeScript 6; its commands work with those versions or newer.
  • A DukaChap owner or manager account with permission to manage products, prices, stock, customer accounts, API keys and metaobjects.
  • A Test key group from API keys: a Storefront endpoint with a publishable and a secret key for the same store (created in step 1).
  • A reachable email inbox for customer and form verification (locally, DukaChap's dev environment delivers these through Mailpit instead of real email — see the checkpoint in step 4), and TEST M-Pesa routing for the payment exercise.
  • AI enabled for your merchant, and ai:write on both the secret key and the endpoint, if you want to complete the assistant step.
  • A Netlify account and a Git repository, only once you reach deployment in step 13.

Use TEST credentials and a TEST store throughout. For account setup, products and stock, see the trader handbook and online store setup guide.

1. Prepare your DukaChap store

  1. Create a branch and a store called Kisumu Kitchen. Follow branch and store setup.
  2. Create three dishes as products — this guide's examples use vegetable rice (KES 350.00), Grilled tilapia (KES 650.00) and Fresh juice (KES 150.00). Set a base unit, a KES price for this branch, receive stock you can actually fulfil, and publish each dish to the store. Follow product publication. A dish with no stock recorded fails at checkout with INSUFFICIENT_STOCK even though it lists a price, so receive real stock before you test checkout in step 8.
  3. Enable customer accounts in the store settings. This guide requires sign-in before ordering, so payment status and receipts can be read through shopper-owned endpoints. See customer accounts.
  4. Confirm TEST M-Pesa routing is configured using payment setup. DukaChap handles the provider credentials and the payment callback; a correctly configured store returns an enabled MPESA_DARAJA method from GET /payment-methods (we check this directly in step 4).
  5. Under Catalogue → Metaobjects, create a table_request type with the fields below — exactly these keys, since the React code in step 9 sends them. Mark every field required except notes.
table_request fields (key: value type)
name: STRING            email: STRING
phone: STRING           preferred_date: DATE
preferred_time: STRING  party_size: INTEGER
notes: STRING (optional)

Under API keys → Create API keys, choose the Kisumu Kitchen store, choose Test, name the group and keep all three items: a Storefront endpoint, a Publishable key and a Secret key. A request can do only what both the endpoint and its key allow, so permissions are the overlap of the two. A credential issued with the default scopes is narrower than what this guide's React code needs, so adjust each item's scopes in the dialog:

PUBLISHABLE key — request:
  products:read, collections:read, metafields:read,
  metaobjects:read, metaobjects:write, media:read,
  carts:read, carts:write, payments:read, subscribers:write

SECRET key — request:
  products:read, collections:read, carts:read, carts:write,
  payments:read, checkouts:write, payments:write,
  customers:read, customers:write, ai:write

Storefront endpoint — request the union of both lists:
  products:read, collections:read, metafields:read,
  metaobjects:read, metaobjects:write, media:read,
  carts:read, carts:write, payments:read,
  checkouts:write, payments:write,
  customers:read, customers:write, ai:write

# Defaults if you accept them: the publishable key gets products:read,
# collections:read, carts:read, carts:write, payments:read and
# subscribers:write. The endpoint gets the secret-key default set, which
# adds checkouts:write, payments:write, orders:read, customers:read and
# customers:write. Neither includes metafields/metaobjects/media, which
# the menu metafield and table-request form need, and the endpoint lacks
# ai:write.
# A publishable key can never be granted checkout, payment-write, order,
# customer or AI scopes, whatever you request.
# Skip ai:write if you don't plan to enable AI, and remove the /api/ai
# proxy rule in steps 4 and 10.
# Add orders:read to the secret key and the endpoint only if you also call
# the guest routes GET /orders/{id} and its receipt routes. Signed-in
# customers read their own orders with their bearer token instead.

Copy the values the dialog shows, because each appears only once: the Storefront endpoint token (sr_…), the Storefront request base URL, the Storefront configuration URL and the two keys. Keep the token and the secret key out of browser code. The endpoint refuses any request without the token, even one with a publishable key, so every call in this guide goes through a small server-side proxy that attaches both.

2. Create your React and TypeScript project

This guide was built with Vite's React + TypeScript template; the DukaChap requests below work the same way with any React setup. These are the exact commands we ran:

npm create vite@latest kisumu-kitchen -- --template react-ts
cd kisumu-kitchen
npm install
npm run dev

Confirm the default page opens at the printed localhost URL, then stop the dev server (Ctrl+C) and continue. Keep the generated package.json, tsconfig*.json and vite.config.ts — we only add to vite.config.ts, in step 4, and never replace it.

One TypeScript default caught us out while writing this guide: Vite's current template enables erasableSyntaxOnly, which rejects constructor parameter-property shorthand (constructor(public status: number) {}). If you see TS1294: This syntax is not allowed when 'erasableSyntaxOnly' is enabled, assign the fields in the constructor body instead — the code in step 3 already does this.

3. Organize your storefront code

Add these files inside src/. This guide builds and tests Menu and Cart as one working screen in App.tsx; sections 7 through 10 give you the account, checkout, table-request and AI calls in the same dukachap() style, to wire into your own additional components the same way.

src/
├── App.tsx            # menu + cart, built and run in this guide
└── lib/
    ├── dukachap.ts     # shared /api request helper
    ├── cart.ts         # menu loading and cart operations
    └── types.ts        # shared API response and component contracts

In src/lib/types.ts, describe the response fields this guide's code reads. These are intentionally narrower than the full API responses — a real GET /products call also returns image and colors fields this guide doesn't use, and a real login response also returns token_type, store_id and customer_id. Extend these types as you use more of a response; TypeScript doesn't validate the JSON at runtime either way.

export interface Product {
  id: string;
  name: string;
  base_unit: string;
  price_minor: number | null;
  currency: string;
  metafields: Record<string, unknown>;
}
export interface ProductPage {
  data: Product[];
  next_cursor: string | null;
}
export interface Availability {
  product_id: string;
  availability: "IN_STOCK" | "LOW" | "OUT_OF_STOCK" | "UNKNOWN";
}
export interface CartIdentity {
  id: string;
  cart_token: string;
  expires_at: string;
}
export interface CartLine {
  id: string;
  product_id: string;
  quantity_base: number;
  unit_price_minor: number;
  line_total_minor: number;
}
export interface CartView {
  id: string;
  status: "OPEN" | "CONVERTED" | "EXPIRED";
  currency: string;
  lines: CartLine[];
  subtotal_minor: number;
  expires_at: string;
}
export interface CustomerSession {
  access_token: string;
  refresh_token: string;
  expires_in: number;
}
export interface Customer {
  customer_id: string;
  display_name: string;
  email: string | null;
}
export interface ChatMessage {
  role: "system" | "user" | "assistant";
  content: string;
}

4. Connect and test your account

Before writing any React code, test the endpoint from a terminal. The request base URLstarts with your dashboard's own address (locally http://localhost:3000, where the dashboard serves the endpoint), then /storefront/<store slug>/ and the first 11 characters of the token. Every storefront route goes after one more /storefront. Send the full token in X-Dukachap-Relay and a matching key in X-Dukachap-Key on every request. We verified this read-only against a local endpoint; these are the requests:

export STOREFRONT_BASE_URL="http://localhost:3000/storefront/kisumu-kitchen/sr_abcd1234"
export RELAY="sr_…"      # the full Storefront endpoint token
export PK="pk_test_…"    # your publishable key
export BASE="$STOREFRONT_BASE_URL/storefront"

curl "$BASE/me" -H "X-Dukachap-Relay: $RELAY" -H "X-Dukachap-Key: $PK"
# {"store_id":"…","store_slug":"kisumu-kitchen","credential_id":"…",
#  "scope":"PUBLISHABLE","environment":"TEST","scopes":[...]}
# "scopes" is the overlap of the key's and the endpoint's scopes.

curl "$BASE/products" -H "X-Dukachap-Relay: $RELAY" -H "X-Dukachap-Key: $PK"
# {"data":[{"id":"…","name":"Grilled tilapia","base_unit":"pcs",
#   "price_minor":65000,"currency":"KES","metafields":{},
#   "image":{"id":"…","url":"/api/v1/media/…","kind":"IMAGE"},
#   "colors":null}, …3 dishes…],"next_cursor":null}

curl "$BASE/payment-methods" -H "X-Dukachap-Relay: $RELAY" -H "X-Dukachap-Key: $PK"
# [{"code":"MPESA_DARAJA","label":"M-Pesa","enabled":true}]

Checkpoint: /me returns your store slug and TEST environment, /products lists your published dishes with real prices, and /payment-methods includes an enabled MPESA_DARAJA. A 401 means a header is missing or wrong (the message says whether it is the key or the relay token); a 403 means the key or the endpoint is missing a scope, and both must allow the call — see API errors. If you enabled customer accounts and set up email locally, DukaChap sends verification mail through Mailpit instead of a real inbox — open http://localhost:8025 to read codes sent in steps 7 and 9.

Send the key in X-Dukachap-Key; the endpoint does not read it from Authorization. Customer routes are stricter: the endpoint allows /customer/* only with a secret key that has customers:read (for GET) or customers:write(for everything else), and the signed-in customer's access token goes in Authorization: Bearer …. Staff routes under /api/v1/admin are not reachable through the endpoint. GET /settings reports customer_accounts_enabled, coming_soon and ai_assistant_enabled, so read it before showing sign-in or chat screens.

Browser code must never see the relay token or the secret key, and because the endpoint rejects any call without the token, the publishable key goes through the proxy too. In development, add a proxy block to the vite.config.ts from step 2. It reads the endpoint and keys from .env.local (never committed), rewrites /api/… to /storefront/… and attaches both headers. We ran an earlier version of this config that called the API directly; the rewrite and the relay header are the only differences, and the endpoint behaviour behind them was verified read-only (step 12):

// vite.config.ts
import react from "@vitejs/plugin-react";
import { defineConfig, loadEnv, type ProxyOptions } from "vite";

const PUBLIC_PATHS = [
  "/me", "/settings", "/products", "/products/", "/media/",
  "/payment-methods", "/carts", "/forms/",
];

export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), "");
  // The Storefront request base URL from the key-group dialog.
  const base = (env.STOREFRONT_BASE_URL ?? "").replace(/\/+$/, "");
  if (!base) throw new Error("Set STOREFRONT_BASE_URL in .env.local");

  const withKey = (key: string | undefined): ProxyOptions => ({
    target: base,
    changeOrigin: true,
    // /api/products -> <base>/storefront/products
    rewrite: (path) => path.replace(/^\/api/, "/storefront"),
    configure: (proxy) => {
      proxy.on("proxyReq", (proxyReq) => {
        if (key) proxyReq.setHeader("X-Dukachap-Key", key);
        if (env.DUKACHAP_RELAY_TOKEN) {
          proxyReq.setHeader("X-Dukachap-Relay", env.DUKACHAP_RELAY_TOKEN);
        }
      });
    },
  });

  return {
    plugins: [react()],
    server: {
      proxy: Object.fromEntries([
        ...PUBLIC_PATHS.map((p) => ["/api" + p, withKey(env.DUKACHAP_PUBLISHABLE_KEY)]),
        ["/api/customer", withKey(env.DUKACHAP_SECRET_KEY)],
        ["/api/checkouts", withKey(env.DUKACHAP_SECRET_KEY)],
        ["/api/ai", withKey(env.DUKACHAP_SECRET_KEY)],
      ]),
    },
  };
});
# .env.local — gitignored by Vite's default template, confirm it stays that way
STOREFRONT_BASE_URL=http://localhost:3000/storefront/kisumu-kitchen/sr_abcd1234
DUKACHAP_RELAY_TOKEN=sr_…
DUKACHAP_PUBLISHABLE_KEY=pk_test_…
DUKACHAP_SECRET_KEY=sk_test_…

This dev proxy is a stand-in for production, not a deployment strategy — step 13 replaces it with a Netlify build plugin that does the same job, attaching the relay token and the key, from environment variables set in Netlify, not a local file.

Create src/lib/dukachap.ts for browser requests. Cart writes (create cart, add line, remove line) and checkout writes (create checkout, complete, start payment) need an Idempotency-Key header. Calling the API directly rejects a missing one with a plain 422, which is what we hit on POST /carts. The endpoint instead adds a random key when you omit one, which would stop a retry from being safe, so always send your own and reuse it when retrying the same action. The helper takes it as an explicit option rather than only on bodies with content. Reads, customer sign-up, sign-in and verification, and form submission do not need one.

// src/lib/dukachap.ts
type RequestOptions = {
  method?: "GET" | "POST" | "DELETE";
  body?: unknown;
  cartToken?: string;
  customerToken?: string;
  idempotencyKey?: string;
};

export class DukachapError extends Error {
  status: number;
  code: string | undefined;
  retryAfter: string | null;

  constructor(message: string, status: number, code: string | undefined, retryAfter: string | null) {
    super(message);
    this.status = status;
    this.code = code;
    this.retryAfter = retryAfter;
  }
}

export async function dukachap<T>(
  path: string,
  { method = "GET", body, cartToken, customerToken, idempotencyKey }: RequestOptions = {},
): Promise<T> {
  const headers = new Headers();
  if (body !== undefined) headers.set("Content-Type", "application/json");
  if (cartToken) headers.set("X-Cart-Token", cartToken);
  if (customerToken) {
    headers.set("Authorization", "Bearer " + customerToken);
    headers.set("X-Customer-Token", customerToken);
  }
  if (idempotencyKey) headers.set("Idempotency-Key", idempotencyKey);
  const response = await fetch("/api" + path, {
    method, headers, cache: "no-store",
    body: body === undefined ? undefined : JSON.stringify(body),
  });
  if (response.status === 204) return undefined as T;
  const data: unknown = await response.json().catch(() => null);
  if (!response.ok) {
    const error = typeof data === "object" && data !== null ? data : {};
    const message = "message" in error && typeof error.message === "string"
      ? error.message : "Request failed (" + response.status + ")";
    const code = "code" in error && typeof error.code === "string" ? error.code : undefined;
    throw new DukachapError(message, response.status, code, response.headers.get("Retry-After"));
  }
  return data as T;
}

6. Add menu details with metafields

A dish's DukaChap product record only has a name, unit, price and stock. A metafield attaches a typed fact — a description, allergens, prep time — to that product, and a published metafield appears automatically in the storefront /products response.

Under Catalogue → Metafields, create a definition with owner type PRODUCT, namespace menu, key description, value type STRING, and storefront visibility enabled. Set its value for vegetable rice to Fresh vegetables with rice. Requesting that product afterwards returns:

curl "$BASE/products/<vegetable-rice id>" -H "X-Dukachap-Relay: $RELAY" -H "X-Dukachap-Key: $PK"
# {
#   "id": "…", "name": "vegetable rice", "base_unit": "",
#   "price_minor": 35000, "currency": "KES",
#   "metafields": { "menu.description": "Fresh vegetables with rice" },
#   "image": { … }, "colors": null
# }

The key in the response is always <namespace>.<key>. Add as many menu.* fields as your menu needs — allergens, prep time, spice level — and render them in Menu.tsx alongside the name and price. A metafield only needs metafields:read on the publishable key; writing one from the admin UI uses your staff session, not the storefront key at all.

7. Add customer accounts

Checkout in this guide requires a signed-in customer. This is the exact sequence we ran: sign up, read the verification code from Mailpit, verify, then log in.

export SK="sk_test_…"   # secret key — the endpoint needs it for /customer/*

curl -X POST "$BASE/customer/signup" -H "X-Dukachap-Relay: $RELAY" -H "X-Dukachap-Key: $SK" \
  -H "Content-Type: application/json" \
  -d '{"email":"asha@example.com","password":"TestPass123!","display_name":"Asha Otieno"}'
# {"account_id":"…","channel":"EMAIL","contact":"asha@example.com",
#  "verification_required":true,"message":"Check your phone or email for the verification code."}

# Locally, open http://localhost:8025 (Mailpit) and read the 6-digit code
# from the "Verify your Kisumu Kitchen account" email.

curl -X POST "$BASE/customer/verify" -H "X-Dukachap-Relay: $RELAY" -H "X-Dukachap-Key: $SK" \
  -H "Content-Type: application/json" \
  -d '{"contact":"asha@example.com","code":"393714"}'
# 204 No Content

curl -X POST "$BASE/customer/auth/login" -H "X-Dukachap-Relay: $RELAY" -H "X-Dukachap-Key: $SK" \
  -H "Content-Type: application/json" \
  -d '{"email":"asha@example.com","password":"TestPass123!"}'
# {"access_token":"eyJ…","refresh_token":"…","token_type":"bearer",
#  "expires_in":900,"store_id":"…","customer_id":"…"}

In Account.tsx, call the same paths through dukachap():

import { dukachap } from "../lib/dukachap";
import type { Customer, CustomerSession } from "../lib/types";

export async function signUp(email: string, password: string, displayName: string): Promise<void> {
  await dukachap<unknown>("/customer/signup", {
    method: "POST",
    body: { email, password, display_name: displayName },
  });
}

export const verifyEmail = (email: string, code: string): Promise<void> =>
  dukachap<void>("/customer/verify", { method: "POST", body: { contact: email, code } });

export const signIn = (email: string, password: string): Promise<CustomerSession> =>
  dukachap<CustomerSession>("/customer/auth/login", { method: "POST", body: { email, password } });

export const readCustomer = (accessToken: string): Promise<Customer> =>
  dukachap<Customer>("/customer/me", { customerToken: accessToken });

The access token is sent as Authorization: Bearer for customer routes and X-Customer-Token for checkout — the helper in step 4 sends both whenever customerToken is set, which is what every call above relies on. Keep tokens in memory only for a frontend-only session; a reload means signing in again. Refresh with /customer/auth/refresh before expires_in (900 seconds here) runs out.

Checkpoint: sign up, enter the wrong code once and confirm it is rejected, then the real code. Sign in, call /customer/me, and confirm a second customer's token cannot read the first customer's account.

8. Take orders and M-Pesa payments

This is the checkout sequence we ran against the running cart and customer token from the sections above — real checkout, order and M-Pesa STK responses, including the two ids that are easy to mix up.

curl -X POST "$BASE/checkouts" -H "X-Dukachap-Relay: $RELAY" -H "X-Dukachap-Key: $SK" \
  -H "X-Cart-Token: <cart_token>" -H "X-Customer-Token: <access_token>" \
  -H "Idempotency-Key: $(uuidgen)" -H "Content-Type: application/json" \
  -d '{"cart_id":"<cart id>","customer_name":"Asha Otieno",
       "customer_phone":"0712345678","customer_email":"asha@example.com",
       "delivery_note":"Milimani, blue gate","gateway":"MPESA_DARAJA"}'
# { "id": "<checkout_id>", "status": "OPEN", "total_minor": 70000,
#   "currency": "KES", "gateway": "MPESA_DARAJA", "sale_id": null,
#   "expires_at": "…" }

curl -X POST "$BASE/checkouts/<checkout_id>/complete" \
  -H "X-Dukachap-Relay: $RELAY" -H "X-Dukachap-Key: $SK" -H "X-Customer-Token: <access_token>" \
  -H "Idempotency-Key: $(uuidgen)"
# { "order_reference": null, "id": "<order_id>", "status": "PENDING_PAYMENT",
#   "total_minor": 70000, "currency": "KES", "created_at": "…", "payment": null }

# Payment attempts are scoped to the CHECKOUT, not the order — using the
# order id here returns 404 "Checkout not found." (we tried it).
curl -X POST "$BASE/checkouts/<checkout_id>/payment-attempts" \
  -H "X-Dukachap-Relay: $RELAY" -H "X-Dukachap-Key: $SK" -H "X-Customer-Token: <access_token>" \
  -H "Idempotency-Key: $(uuidgen)" -H "Content-Type: application/json" \
  -d '{"phone":"0712345678"}'
# { "attempt_id": "…", "state": "CUSTOMER_ACTION_PENDING", "reused": false,
#   "message": "Payment request sent to the customer's phone." }

curl "$BASE/customer/orders/<order_id>" -H "X-Dukachap-Relay: $RELAY" -H "X-Dukachap-Key: $SK" \
  -H "Authorization: Bearer <access_token>"
# { …, "status": "PENDING_PAYMENT",
#   "payment": { "attempt_id": "…", "state": "CUSTOMER_ACTION_PENDING",
#                "confirmation_source": null } }

POST /checkouts also accepts an optional discount_code; the checkout response then reports discount_code and discount_minor alongside total_minor. Once an order exists, the signed-in customer can list their orders (GET /customer/orders), read a receipt (GET /customer/orders/<id>/receipt as JSON, …/receipt/pdf as a PDF), have it emailed (POST …/receipt/email, which returns 204) and confirm an M-Pesa payment by submitting the code from their M-Pesa message (POST …/verify-payment-code with {"code": "…"}). We checked these routes against the API source and did not run them in this guide.

Offer M-Pesa only when GET /payment-methods returns an enabled MPESA_DARAJA method (step 4). Save a checkout journal — cart id, checkout id, a distinct Idempotency-Key for each of the three writes above — before the first request, and reuse the same keys and payload on a retry after a reload. UNKNOWN and REVIEW_REQUIRED payment states need manual reconciliation in DukaChap, not another automatic prompt.

Checkpoint: complete a TEST payment and confirm the order shows as paid in DukaChap once the sandbox callback lands. Repeat the /complete call with the same idempotency key and confirm it returns the identical order rather than creating a second one. See checkout and payment and orders and receipts for the full contracts.

9. Receive verified table requests

This uses the table_request metaobject type you created in step 1. This exact sequence — submit, wrong code, correct code — is what we ran:

curl -X POST "$BASE/forms/table_request/submit" -H "X-Dukachap-Relay: $RELAY" -H "X-Dukachap-Key: $PK" \
  -H "Content-Type: application/json" \
  -d '{"values":{"name":"Asha Otieno","email":"asha.table@example.com",
       "phone":"0712345678","preferred_date":"2026-12-18",
       "preferred_time":"18:30","party_size":4,
       "notes":"An accessible table, please"}}'
# { "entry_id": "<UUID>", "verification_required": true }

# Mailpit: "Verify your message to Kisumu Kitchen" → 6-digit code

curl -X POST "$BASE/forms/table_request/verify" -H "X-Dukachap-Relay: $RELAY" -H "X-Dukachap-Key: $PK" \
  -H "Content-Type: application/json" \
  -d '{"entry_id":"<same UUID>","code":"000000"}'
# 400 { "code": "VERIFICATION_FAILED", "message": "This code is invalid or has expired." }

curl -X POST "$BASE/forms/table_request/verify" -H "X-Dukachap-Relay: $RELAY" -H "X-Dukachap-Key: $PK" \
  -H "Content-Type: application/json" \
  -d '{"entry_id":"<same UUID>","code":"106372"}'
# 200 { "verified": true }

This call needs metaobjects:write on the publishable key — the scope the default PUBLISHABLE key does not have (step 1). Forgetting it is the single most common reason this request fails with "This API key is not scoped for 'metaobjects:write'." , which is the exact error we got before re-issuing the key with explicit scopes.

In Catalogue → Metaobjects → Table requests, staff see the entry's submission status and act only on VERIFIED ones — PENDING_VERIFICATION does not confirm a real customer. Turning a verified request into an actual capacity check is a staff-only API call, covered in section 11.

Checkpoint: submit a request, try the wrong code, then the real one, and confirm the entry shows VERIFIED in the admin UI.

10. Add an AI menu guide

This needs AI enabled for the merchant and a secret key scoped with ai:write. DukaChap offers two routes for a menu guide: POST /ai/text, plain generation where you write the prompt (built below), and POST /ai/assistant, a built-in storefront assistant with catalogue and order tools (described at the end of this step). provider on /ai/text is deepseek (the default) or openai. This is the real question and real answer we got back from /ai/text against the Kisumu Kitchen catalogue:

curl -X POST "$BASE/ai/text" -H "X-Dukachap-Relay: $RELAY" -H "X-Dukachap-Key: $SK" \
  -H "Content-Type: application/json" \
  -d '{"provider":"deepseek","max_tokens":350,"temperature":0.3,
       "messages":[
         {"role":"system","content":"You are the menu guide for Kisumu Kitchen."},
         {"role":"user","content":"Niko na KES 600. Unapendekeza nini?"}
       ]}'
# {
#   "provider": "deepseek", "model": "deepseek-flash",
#   "text": "Na KES 600, unaweza kupata milo mitatu ya bei nafuu au
#            milo miwili ya kawaida. …",
#   "prompt_tokens": 27, "completion_tokens": 342
# }

In MenuAssistant.tsx, build the same request from your loaded catalogue and recent messages:

import { dukachap } from "../lib/dukachap";
import type { ChatMessage, Product } from "../lib/types";

const assistantInstructions =
  "You are the menu guide for Kisumu Kitchen in Kisumu. Answer in friendly " +
  "English or Kiswahili, matching the customer. Recommend only dishes in the " +
  "supplied catalogue. Ask staff about allergies; never guarantee allergen " +
  "safety. Staff confirm tables and delivery. Checkout handles payment. " +
  "Never request an M-Pesa PIN, password or verification code.";

export async function askMenuGuide(
  products: Product[], recentMessages: ChatMessage[], question: string,
): Promise<string> {
  const context = assistantInstructions + " Catalogue data: " + JSON.stringify(
    products.map(({ id, name, price_minor, currency }) => ({ id, name, price_minor, currency })),
  );
  if (context.length > 8000) throw new Error("Narrow the menu context before sending.");
  const answer = await dukachap<{ text: string }>("/ai/text", {
    method: "POST",
    body: {
      provider: "deepseek", max_tokens: 350, temperature: 0.3,
      messages: [{ role: "system", content: context }, ...recentMessages.slice(-12),
        { role: "user", content: question }],
    },
  });
  return answer.text;
}

This is prompt customization, not model fine-tuning. With /ai/text the model only sees the catalogue you send, so it has no order lookup or mutation tools; use /ai/assistant if you want those. Render its reply as plain text, never as HTML; it is not a payment confirmation and never should be treated as one. Refer allergy questions to staff — the system prompt above says so, but a model can still be wrong, so staff remain the actual safety check.

Checkpoint: ask a budget question in Kiswahili and in English and confirm both get a relevant, priced answer; check AI usage against your budget in DukaChap afterwards.

The built-in storefront assistant. POST /ai/assistant takes the same secret key and ai:writescope, and runs a bounded tool loop for you. It can search products, check stock, read product details, suggest items that go together, look up the signed-in customer's order status, hand off to a human, and propose a return, which waits in a staff approval queue. It cannot change a cart, an order or an account. We checked this against the API source; we did not run it in this guide.

curl -X POST "$BASE/ai/assistant" -H "X-Dukachap-Relay: $RELAY" -H "X-Dukachap-Key: $SK" \
  -H "Content-Type: application/json" \
  -d '{"messages":[{"role":"user","content":"Niko na KES 600. Unapendekeza nini?"}],
       "customer_id":"<signed-in customer id, optional>"}'
# { "text": "<a JSON string, described below>" }

The text value is itself a JSON string, rebuilt on the server: reply (the answer), options (short quick replies), productIds (catalogue ids you can render as product cards) and action (contact, track, signin or a custom action your store defines, otherwise null). Parse it with JSON.parse. Anything malformed is replaced with a safe hand-off reply before it reaches you. Pass customer_id only for a customer your own server has authenticated; order lookups report NOT_SIGNED_IN without it.

The merchant shapes the assistant in the store's AI profile: an on/off switch, assistant name, business type, brand voice, language (for example en or sw), policies and custom actions. With the switch off, every turn returns the hand-off reply and no model is called. Calls are rate limited per store and count against the merchant's daily AI budget (AI_BUDGET_EXCEEDEDwhen it runs out).

11. Staff workflows: bookings and delivery

Turning a verified table request into a real reservation, and a paid order into a delivery, both use DukaChap's staff API — a different base path (/api/v1/admin/…), a staff bearer token, not a storefront key, and permissions booking.manage / fulfilment.manage. The Storefront endpoint does not forward these routes. We verified the request and response shapes against the DukaChap API source; run them from your staff tooling, never from the public React app.

# Create a table and its Friday opening window (weekday 0 = Monday)
POST /api/v1/admin/booking/resources
{ "branch_id": "<branch UUID>", "name": "Table 4", "kind": "TABLE",
  "capacity": 4, "timezone": "Africa/Nairobi" }

POST /api/v1/admin/booking/resources/<resource UUID>/availability
{ "weekday": 4, "start_time": "12:00:00", "end_time": "22:00:00" }

# Confirm the verified table request as an actual booking
POST /api/v1/admin/booking/bookings
{ "branch_id": "<branch UUID>", "resource_id": "<resource UUID>",
  "customer_name": "Asha Otieno", "customer_phone": "0712345678",
  "customer_email": "asha@example.com", "party_size": 4,
  "starts_at": "2026-12-18T18:30:00+03:00", "ends_at": "2026-12-18T20:00:00+03:00",
  "notes": "Verified table request <entry UUID>" }
# One-time setup: an included-delivery method and zone
POST /api/v1/admin/fulfilment/methods
{ "code": "local-delivery", "name": "Local delivery included",
  "kind": "DELIVERY", "enabled": true, "fee_minor": 0 }

POST /api/v1/admin/fulfilment/zones
{ "method_id": "<method UUID>", "name": "Kisumu local",
  "fee_minor": 0, "areas": ["Milimani", "Kisumu CBD"] }

# Per paid order: create the fulfilment, then move it through status
POST /api/v1/admin/fulfilment/orders
{ "sale_id": "<order id from the admin order view>", "method_id": "<method UUID>",
  "address": { "recipient_name": "Asha Otieno", "phone": "0712345678",
    "line1": "Building and room from the order's delivery note",
    "city": "Kisumu", "country": "KE" } }

PATCH /api/v1/admin/fulfilment/orders/<fulfilment UUID>/status
{ "status": "READY", "note": "Kitchen has packed this order" }
# Then DISPATCHED, then FULFILLED, each a separate staff action.

Allowed values, from the API source: a resource kind is STAFF, ROOM, TABLE, EQUIPMENT, CLASS or OTHER; booking statuses are PENDING, CONFIRMED, COMPLETED, CANCELLED and NO_SHOW; a fulfilment method kind is PICKUP, DELIVERY, SHIPPING or DIGITAL; fulfilment statuses are PENDING, SCHEDULED, READY, DISPATCHED, FULFILLED and CANCELLED, and a status update can carry a tracking_ref.

Confirm PAID in DukaChap before releasing food. There is currently no shopper-facing delivery-tracking endpoint — staff notify the customer through their normal contact channel. A delivery zone sets a fee staff can see; it does not add a fee to the storefront checkout automatically.

12. What was tested, and what you still must test

The menu, cart, account, payment and table-request examples were run against a local DukaChap API for a real test store while writing this guide, calling the API directly. When the issued Storefront endpoint became the documented route, we re-verified its URL shape, headers and permissions with read-only requests, but did not re-run the write steps through it. Here is exactly what each row covered, and what is still on you before you rely on this in your own project

Covered in this guideHow it was verified
Menu load, cart create/add/removeBuilt, run with npm run dev, and clicked through in a browser against a live store.
Issued Storefront endpoint: URL shape, headers and permissionsVerified with read-only requests to a local endpoint on 17 November 2026: /me, /settings, /payment-methods and /products succeeded, a missing relay header or key returned 401, a publishable key on /customer/* returned 403, and a path outside /storefront returned 404. Writes through the endpoint were not run.
Vite dev proxy attaching keys by pathConfirmed the proxied /api/products request reached the real backend and returned real dishes. That run called the API directly, before the issued endpoint became the documented route.
Signup, email verify (via Mailpit), loginRun with curl; a wrong code was confirmed to fail before the right one succeeded.
Checkout create → complete → M-Pesa payment-attemptRun with curl against the sandbox gateway; the STK push request was accepted and the order reflected the pending payment state.
Table-request form submit → wrong code → verifyRun with curl; required reissuing the publishable key with metaobjects:write first.
Product metafield (menu.description)Set from the service layer and confirmed in the next /products response.
/ai/text menu guideRun with curl against the real DeepSeek provider configured for this backend.
/ai/assistant, receipts and payment-code routesNot run in this guide. Described from the API source. Test them against your own store.
Staff booking and fulfilment APIsNot run end-to-end. Checked against the DukaChap API source for request fields, allowed values and permissions, not exercised against a live resource and booking. Test these yourself before relying on them.
Netlify deployment (step 13)Not deployed in this guide. The proxy logic mirrors the dev proxy that was tested, but a Netlify build and preview were not run here.

Before you open this to real customers, you additionally need to check on your own account: concurrent-edit and expired-cart behaviour under load, every M-Pesa outcome (cancel, timeout, failure — only the happy path was exercised above), credential handling in a production build (inspect the built JS and network requests for leaked keys), and accessibility and mobile layout, none of which this guide verified.

13. Deploy your React project to Netlify

This step was not run against a live Netlify account while writing this guide — treat it as the documented, recommended pattern, and re-run the checkpoints from steps 4 through 10 against your deploy preview before trusting it.

  1. Push your project to Git, including its lockfile. Keep .env.local and dist/out of Git — Vite's default .gitignore already does this.
  2. Import the repository into Netlify with build command npm run build and publish directory dist.
  3. Create plugins/dukachap-proxy/index.js doing the same job as the Vite proxy in step 4 (rewrite to the endpoint, attach the relay token and key), but as a Netlify build plugin writing redirect rules instead of proxying live requests. Register it in netlify.toml:
    # netlify.toml
    [[plugins]]
      package = "./plugins/dukachap-proxy"
  4. Set STOREFRONT_BASE_URL, DUKACHAP_RELAY_TOKEN, DUKACHAP_PUBLISHABLE_KEY and DUKACHAP_SECRET_KEY in Netlify with Builds scope, using matching TEST values for previews and branch deploys.
  5. Deploy, then repeat the checkpoints from steps 4–10 against the preview URL before pointing a custom domain at it and switching to LIVE credentials.

Before taking live orders

This guide gets you a working menu, cart, account, M-Pesa checkout, table request and AI guide, each exercised against a real backend at least once. It does not establish your account's live payment eligibility, reliable email delivery at volume, staff coverage, or measured capacity under real traffic — agree on who handles an uncertain payment, a rejected table request or a failed delivery before you accept money from strangers.

Continue with the API reference, store setup guide and trader handbook as your store grows.