Building an E-Commerce Site from Scratch with an AI Coding Assistant: A Practical Guide
This article explains how to use an AI coding assistant to build a frontend-only e-commerce demo. It covers task decomposition, technology stack selection, routing, state management, shared components, prompt templates, privacy considerations, and debugging. The focus is on validating frontend fundamentals rather than building a production-ready store.
1. Defining the scope first
This guide focuses on a pure frontend e-commerce demo: all data comes from local mocks, and it does not include real checkout or payment. It can validate routing, component reuse, state flow, and form validation—core frontend skills.
For production, you still need backend APIs, a payment gateway, real authentication and risk control, data compliance approval, and performance evaluation such as first-screen time, bundle size, and API latency. Treat the demo as a skeleton validator rather than a launch-ready store; only then will expectations stay aligned.
AI coding assistants are especially useful in e-commerce projects because they involve many pages, many forms, and repeated layouts. These are low-creativity, high-volume tasks that are well suited to batch generation. The development paradigm also shifts from “humans write code while machines autocomplete” to “humans describe intent, machines generate, and humans review.”
2. Task decomposition: from vague requirements to an executable checklist
AI output quality depends heavily on input clarity. A vague instruction such as “build a shopping website” will likely produce a disorganized structure. A practical approach is to break the request into three parts: technology stack + page list + acceptance criteria. The technology stack must be specified at a verifiable level:
Technology stack (version locked):React 18.3.1 + Vite 5.4 + react-router-dom 6.26State management: zustand 4.5 (three stores: cart / order / user)Data: local mocks in src/mocks; interfaces are reserved in the services layerStyling: CSS Modules or Tailwind; only a reset remains globalInitialization and commands:npm create vite@latest ecommerce-demo -- --template reactcd ecommerce-demo && npm i react-router-dom zustandnpm run dev # http://localhost:5173npm run build # build verificationPage list (10 pages total):1. Home (product list) 6. User registration2. Product detail 7. User center - Dashboard3. Checkout 8. User center - Orders4. Order success 9. User center - Wallet / Coupon package5. User login 10. User center - SettingsAcceptance criteria:- All 10 routes are directly accessible without blank screens; refresh does not return 404- Add to cart → checkout → submit → success page has consistent state across the full flow- When the login state expires, visiting /user/* automatically redirects to login- Login, registration, and address forms include required-field and format validation
Three common long-tail questions:
- How should the page list be divided? Divide it by the user task chain—browse → decide → pay → fulfill → account—not by slicing visual designs. Dividing by task chain makes missing steps obvious; dividing by visuals easily misses pages such as success pages and empty states, which often have no main visual.
- How should acceptance criteria be defined? Write only items that are checkable, reproducible, and binary. “Smooth experience” is not an acceptance item; “refreshing /user/orders does not show a blank screen” is.
- Where do common failures occur? Pages are created but not registered in the routing table; mock fields do not match the fields expected by the services layer; state is scattered across multiple components’ local
useState, causing cross-page inconsistency.
3. Implementation steps from 0 to 1
- Initialize: Create a React project with Vite, confirm that
npm run devstarts successfully, then hand it over to the AI. - Define the directory structure: Put the directory conventions into the prompt first; all later generation should follow them.
- Install dependencies: Install
react-router-domand the state library up front to prevent the AI from introducing a second state solution midway. - Configure routing: First create only the routing table and empty page components. Make navigation work before filling in content.
- Register pages: Every new page must complete three things: create the file, add the route, and add the entry link. Missing any one of them can cause a blank screen.
- Extract shared components: Extract the navigation bar, footer, product card, form controls, empty state, and error state into shared components first. Page-level components should mainly handle composition.
- Run acceptance checks: Make sure
npm run buildpasses and verify each item in the acceptance checklist one by one.
4. Page system and key interactions
The internal logic of the three major modules determines how components should be organized:
- Product browsing: The home page focuses on a responsive card grid and filtering. The product detail page carries images, price, specifications, and inventory.
- Transaction conversion: Checkout and order-success pages form the conversion funnel, and every step needs a clear status prompt. Cart state should be centralized in one store, with fields such as
{ skuId, title, price, qty }. The total price should be derived through a selector rather than stored separately. Orders should follow a state machine:pending_pay → paid → shipped → completed, withclosedas another terminal state. Each state should map to exactly one label and allowed action set, preventing logic gaps such as allowing cancellation after shipment. - User center: There are six pages: login, registration, dashboard, orders, wallet, and settings. Protect
/user/*with a login guard (aRequireAuthlayout component). When no token is present, redirect to login and preserve the return address. All list pages must implement empty and error states; success branches alone are not enough.
5. Prompt engineering: reusable templates and a minimum skeleton
Four principles: define boundaries and constraints clearly; build the skeleton before details; provide acceptance criteria; and keep context within the same session.
Reusable prompt template:
Target page: User center - OrdersTechnology stack: React 18 + zustand + CSS Modules (no UI library)Directory constraints: components in src/components; stores in src/storeReuse requirement: must use existing Card / Table / Empty componentsAcceptance criteria: status cards + table + empty state; fields come from src/mocks/orders.jsProhibitions: do not modify the router configuration, do not add dependencies, do not write inline stylesOutput format: 1) assumptions and reasoning 2) full file code 3) verification command
Directory tree and routing table (skeleton first):
src/├── main.jsx # BrowserRouter wrapped entry├── App.jsx├── router/index.jsx # Single routing table├── layouts/StoreLayout.jsx + RequireAuth.jsx├── components/ # NavBar Footer ProductCard Card Table FormField Empty ErrorState├── pages/ # Home ProductDetail Checkout OrderSuccess Login Register│ └── user/ # Dashboard Orders Wallet Settings├── store/ # cartStore userStore orderStore├── services/ # Real API call placeholders (currently returning mocks)└── mocks/ # products.js orders.js user.js
// src/router/index.jsximport { createBrowserRouter } from 'react-router-dom';export const router = createBrowserRouter([{path: '/',element: <StoreLayout />,children: [{ index: true, element: <Home /> },{ path: 'product/:id', element: <ProductDetail /> },{ path: 'checkout', element: <Checkout /> },{ path: 'order-success/:orderId', element: <OrderSuccess /> },{ path: 'login', element: <Login /> },{ path: 'register', element: <Register /> },{path: 'user',element: <RequireAuth />,children: [{ index: true, element: <Dashboard /> },{ path: 'orders', element: <Orders /> },{ path: 'wallet', element: <Wallet /> },{ path: 'settings', element: <Settings /> },],},{ path: '*', element: <NotFound /> },],},]);
// src/pages/user/Orders.jsximport { Card } from '../../components/Card';import { Table } from '../../components/Table';import { Empty } from '../../components/Empty';import { useOrderStore } from '../../store/orderStore';import { ORDER_STATUS } from '../../constants/order';export default function Orders() {const orders = useOrderStore((s) => s.orders); // Single source of truthif (!orders.length) {return <Empty text="No orders yet" to="/" action="Go browse" />;}return (<Card title="My Orders"><Tablecolumns={['Order ID', 'Order Time', 'Product', 'Amount', 'Status']}data={orders}renderStatus={(s) => ORDER_STATUS[s].label}/></Card>);}
// src/mocks/orders.jsexport const orders = [{id: 'NO20260826001',createdAt: '2026-08-26 10:12',items: [{skuId: 'sku-001',title: 'Mechanical Keyboard',price: 399,qty: 1,},],amount: 399,status: 'pending_pay', // pending_pay|paid|shipped|completed|closed},];
6. UI usability and privacy protection
The usability of an AI tool is not determined only by generation quality. It also depends on interaction: whether the context preview is clear, whether changes can be reviewed and compared item by item, and whether partial diffs can be accepted selectively. These factors directly affect review cost.
For privacy, check the data processing policy item by item:
- Do not upload secrets: Add
.env.localto.gitignore. Before pasting code into a tool, replace API keys and database connection strings with placeholders. - Desensitize data: Replace real phone numbers, addresses, and order IDs with mock values or apply masking.
- Retention and training: Confirm whether conversation content is retained, whether it is used for model training, and whether retention can be disabled. Check whether an enterprise version offers a zero-retention option.
- Compliance approval: Finance, healthcare, government, and enterprise scenarios may require internal security review and a Data Processing Agreement (DPA).
- Team management: Standardize model and permission settings, and retain usage audit records.
7. Debugging and iteration: common error checklist
There is rarely such a thing as a perfect result on the first generation. It is normal for code to run but still contain errors, layout issues, or missing logic. The key is to iterate in small steps: verify page by page instead of testing only after everything is finished, let the tool read error messages and self-correct, and manually review critical logic such as authentication, payment, and validation.
| Symptom | Check first | Fix prompt focus |
|---|---|---|
| Blank routing page / 404 on refresh | Whether BrowserRouter wraps the app, path spelling, capitalization |
Attach the full stack trace; only allow changes to the router and current page |
| Component import failure | Mismatch between default exports and named exports, file-name case sensitivity, circular dependencies | Require a consistent export style and list import relationships |
| Inconsistent state | Multiple copies of the same data; total price not derived through a selector | Require convergence into a single store + selector |
| Missing form validation | No unified FormField; input not trimmed before submission |
Require required-field validation + regex + error message text |
| Style misalignment | CSS Modules not taking effect; global style conflicts; container missing flex | Require changes only to style files; provide the render structure |
Unified fix prompt format:
Symptom: Clicking a product card on the home page changes the URL to /product/1, but the page is blankReproduction: npm run dev → click the cardError: <paste the full console stack trace>Expected: Render ProductDetail and display product informationConstraints: Only modify src/router/index.jsx and src/pages/ProductDetail.jsxOutput: Cause analysis → code diff → verification command
A common result from the first round is “starts but throws errors, all images are placeholders, and the detail page contains only a title.” You can refine it step by step with follow-up prompts: add price, inventory, and specification selection to the detail page; replace placeholder images with a configurable placeholder component. After three to five iterations, you can usually obtain a structurally complete product.
8. Evolution trends and tool selection considerations
AI coding tools are evolving from code completion toward task-level autonomous execution. The competition is no longer about whether they can generate code, but about accuracy, deep understanding of project context, and how well they fit the developer workflow. Major cloud providers and IDE vendors are integrating code generation, intelligent Q&A, and debugging assistance into a unified development environment.
When selecting tools, return to real requirements: whether the required technology stack is supported, whether the data processing policy is compliant, whether diff review and debugging are smooth, and whether context remains consistent across long sessions. Instead of comparing tool counts or concepts, it is often more useful to run the full e-commerce demo workflow described above and see whether the tool can deliver reliably.
Tools are ultimately amplifiers. Clear architecture decisions and rigorous code review remain the fundamentals that determine delivery quality.
