Building an E-commerce Frontend from Scratch with AI Coding Tools: From Prototype to Production

    AI coding tools can scaffold an entire e-commerce frontend in one pass, but code that runs is not the same as code that's ready to ship. This article lays out a reusable, AI-assisted workflow for building an e-commerce frontend with React—covering task design with verifiable requirements, data contracts, a layered architecture, and page-by-page implementation of product detail, checkout, purchase success, login, registration, and the user center. It then addresses the common quality problems in AI-generated code (first-run errors, coupled mock data, missing styles, poor mobile layout, incomplete validation, placeholder images, and slow iteration) with concrete fixes, shows how to bring the output into a quality system through type checking, unit tests, end-to-end smoke tests, and CI, and offers a framework for objectively evaluating AI coding tools.

    Introduction: From “It Runs” to “It Ships”

    With feature planning, code generation, and quality assessment, AI coding tools are becoming a “copilot” for developers building new projects. Faced with a comprehensive task like “build an e-commerce site from 0 to 1,” an agent can already plan the route structure, create multiple pages, organize components, and generate usable initial code in a single pass. But in practice, one generation does not equal one usable result. Common problems include:

    • The project errors out on first launch and needs repeated patching;
    • White-on-white text buttons, mobile pages without responsiveness, and lots of placeholder images;
    • Incomplete form validation;
    • Mock data entangled with page logic.

    Behind these symptoms is the gap between what AI is good at (“generating code”) and what engineering delivery requires (“meeting standards”). Using a React-based e-commerce frontend as an example, this article covers the implementation essentials of core pages—product detail, purchase, purchase success, login, registration, and user center—and lays out a reusable AI-collaboration development path. The goal is to help developers use tools like Baidu AI Cloud’s intelligent coding assistant to move generated results from “it runs” to “it’s deliverable.”

    1. Task Design: Steer AI with Verifiable Requirements

    The quality of AI-generated code depends heavily on how clearly the requirements are stated. Vague instructions like “write a shopping site with framework X” force the model to fill in implicit decisions—data models, state management, styling conventions—on its own, and implementations across different pages easily contradict each other. So before writing any code, complete three definitions.

    Page Inventory and Route Planning

    A typical page structure for an e-commerce frontend:

    • Shopping flow: Product detail → Checkout → Purchase success;
    • Account system: Login, registration;
    • User center: Dashboard, orders, wallet (coupons), settings.

    Two principles for route planning:

    • Use centralized routing configuration, e.g. /product/:id, /checkout, /order/success/:orderNo, instead of hardcoding;
    • Add a login guard to the user center that redirects unauthenticated users to the login page and returns them to the original URL after a successful login.

    Data Contracts First

    Data passed between pages should be agreed upon in advance as enumerable fields and states—a “source of truth” when generating code. An example structure:

    1. // types.ts: data contract shared by frontend and backend
    2. export interface Product {
    3. id: string;
    4. name: string;
    5. priceCents: number; // store all amounts as integer cents to avoid floating-point errors
    6. stock: number;
    7. images: string[]; // main image + detail images
    8. description: string;
    9. }
    10. export interface Order {
    11. orderNo: string;
    12. items: { productId: string; quantity: number }[];
    13. totalCents: number;
    14. status: 'created' | 'paid' | 'cancelled';
    15. createdAt: string;
    16. }
    17. export interface Coupon {
    18. id: string;
    19. name: string;
    20. amountCents: number;
    21. expireAt: string;
    22. }

    Storing and calculating money as integer cents is standard practice in e-commerce. Representing currency with floating-point numbers can introduce rounding errors when summing and comparing, causing reconciliation problems in scenarios like coupon deductions and order totals. Stating this explicitly in the prompt significantly reduces later rework.

    Acceptance Criteria

    Write a “Definition of Done” into the task description up front so AI can self-check during generation:

    • The full shopping flow works end to end: browse product → login/register → checkout → place order → find it in the order list;
    • Every form has client-side validation with clear error messages;
    • Both desktop and mobile display correctly, with no horizontal scrolling and no overlap;
    • The code produces no console errors and the build passes.

    Prompt Skeleton

    Module Purpose Example
    Role and goal Define the tech stack and delivery scope Build an e-commerce site with a mainstream functional-component framework + TypeScript + a frontend router
    Pages and routes Define page boundaries List 9 pages with their paths and login-guard rules
    Data model Unify fields and states Reference the Product/Order/Coupon type definitions
    Engineering conventions Constrain directory structure and styling system Layer pages, components, state, and data fetching; manage theme colors with CSS variables
    Acceptance criteria Provide checkable completion conditions Working shopping flow, complete form validation, usable on mobile, no console errors

    Also instruct in the prompt to “output a task plan before implementing,” and guide the tool to execute step by step and report progress promptly. Clear requirement input often saves more time than repeatedly debugging generated output.

    2. Architecture First: Don’t Let AI Just “Pile Up Pages”

    Many AI-generated projects are “oversimplified in architecture”: all logic is concentrated in a few files, styles and logic are mixed together, and mock data is scattered across pages. As the number of pages grows, maintenance and extension costs rise quickly. The right approach is to define the skeleton first, then let AI fill it in block by block. A reference directory structure:

    1. src/
    2. ├── router/ # centralized routing config, login guard
    3. ├── layouts/ # layout components (e.g., user-center sidebar layout)
    4. ├── pages/ # page-level components, orchestration only
    5. ├── components/ # reusable UI components (buttons, forms, product cards, etc.)
    6. ├── services/ # data access layer, connects to mock or real APIs
    7. ├── stores/ # global state (cart, user info)
    8. ├── schemas/ # form validation rules
    9. └── styles/ # design tokens and global styles

    Three points are worth noting:

    1. Separate pages from data access: Pages fetch data through the services layer, so switching the underlying implementation from mock data to real APIs requires no changes to page code.
    2. Unified design tokens: Colors, spacing, border radius, and font sizes are managed by CSS variables, preventing AI from picking colors arbitrarily across pages and eliminating problems like insufficient contrast (e.g., white text on a white background).
    3. Shared type contracts: Data structures and API return types are maintained centrally, making type checking the “first line of defense” against errors.

    3. Page-by-Page Implementation: Key Nodes of AI Collaboration

    Login and Registration

    Login and registration are among the page types AI generates best, usually completed in one pass, but details still need scrutiny.

    • Field validation: Email format, password length, matching of two password entries, phone number format, etc. Centralize validation rules into reusable schemas, sharing field definitions between login and registration to avoid inconsistent rules.
    1. // schemas/auth.ts
    2. export const loginSchema = {
    3. account: { required: true, message: 'Please enter your email or phone number' },
    4. password: { required: true, min: 8, message: 'Password must be at least 8 characters' },
    5. };
    6. export const registerSchema = {
    7. ...loginSchema,
    8. confirmPassword: {
    9. required: true,
    10. // the validator must be linked with the password field
    11. validator: (value: string, all: Record<string, string>) =>
    12. value === all.password || 'The two passwords do not match',
    13. },
    14. };
    • Session persistence: Save credentials after a successful login so the user’s state isn’t lost on refresh. Prefer storing credentials in HttpOnly cookies to reduce the risk of theft via cross-site scripting (XSS); avoid saving long-term credentials in frontend-readable storage.
    • Error messages: Distinguish “account doesn’t exist,” “wrong password,” and “network error,” while avoiding leaks of sensitive information such as whether an account exists.
    • Form security: Disable the submit button before submission to prevent duplicate submissions; escape output so user input isn’t executed as HTML.
    • Post-registration onboarding: Auto-login after registration and redirect back to the previously restricted page.

    Product Detail Page

    Detail pages are information-dense, and the common generation problem is “too simple”—just a title, a price, and a placeholder image.

    • Structured display: Main product image, price, stock, spec selection (e.g., color/size), quantity adjustment, add-to-cart and buy-now entries, rich text/media details, and related recommendations.
    • Visual assets: Use a placeholder image service to generate sample images of different sizes, or configure replaceable asset URLs at the data layer. Show a fallback image when loading fails to avoid broken images.
    • Interaction states: Prompt when no spec is selected and “buy now” is clicked; set the button to “sold out” when stock is zero.

    Checkout Page

    The checkout page involves amount calculations and has the highest fault-tolerance requirements.

    • Cost breakdown: List item subtotal, coupon deduction, shipping, and amount due item by item;
    • Integer arithmetic: Calculate all amounts in cents;
    • Stock and submission: Show stock; disable the button when submitting an order;
    • API idempotency: Generate an idempotency key (a unique request identifier) on the frontend and send it with the request, so the server can deduplicate repeated requests. This prevents double orders from rapid clicks and handles safe retries after network timeouts.
    1. // services/order.ts
    2. export async function createOrder(payload: CheckoutPayload): Promise<Order> {
    3. const idempotencyKey = crypto.randomUUID();
    4. return http.post<Order>('/api/orders', payload, {
    5. headers: { 'Idempotency-Key': idempotencyKey },
    6. });
    7. }

    Purchase Success Page

    The success page itself is simple; what matters is the source of state and its reachability:

    • Display the order number, amount due, payment method, and estimated delivery information;
    • Page data should come from an order query API. If the generated result reads directly from cart state, users may get wrong data when refreshing or entering from the order list;
    • Provide “view order” and “continue shopping” entries, and handle cases where the order doesn’t exist or the link is invalid.

    User Center: Dashboard, Orders, Wallet, and Settings

    The user center is the core area for testing whether generated code has “architectural capability.” Four sub-pages have similar structure but different data, making them good candidates for a shared layout:

    • Unified layout: Sidebar navigation + main content area, with sub-pages rendered through nested routes;
    • Dashboard: Summary cards for recent orders, coupon count, account balance, etc.;
    • Orders: Status filtering (all/unpaid/completed/cancelled), a paginated list, and actions like cancel order and buy again;
    • Wallet (coupons): Balance display, coupon list, and expiration status markers;
    • Settings: Profile editing, password change, etc., with the same validation needs.

    Each sub-page should share the same loading, empty-state, and error-state handling logic rather than each page writing its own.

    4. Common Quality Problems in AI-Generated Code and How to Fix Them

    From a full e-commerce frontend build, we can distill the following high-frequency problems and the corresponding “manual takeover” methods.

    Crashes on First Run

    When AI generates a multi-file project, wrong module import paths, missing dependencies, and mismatched imports/exports are common causes. Require the tool to run a build or start command for self-checking before delivery, and read the error stack to pinpoint the specific file. If the generation tool can execute terminal commands, this step can greatly reduce the rounds of “patching until it looks right.”

    Mock Data Coupled with Business Logic

    Data written directly in page components is the thorniest problem when connecting real APIs later. To fix:

    • Consolidate data fetching into the services layer; pages consume only Promises;
    • Switch between mock and real APIs via environment variables.
    1. // services/http.ts
    2. const USE_MOCK = import.meta.env.VITE_USE_MOCK === 'true';
    3. export const http = {
    4. async get<T>(url: string): Promise<T> {
    5. if (USE_MOCK) return mockAdapter(url) as Promise<T>;
    6. const res = await fetch(url, { credentials: 'include' });
    7. if (!res.ok) throw new Error(`Request failed: ${res.status}`);
    8. return res.json() as Promise<T>;
    9. },
    10. // post / put / delete are wrapped the same way
    11. };

    Missing Style System

    This shows up as arbitrary colors, white-on-white text, and inconsistent styles across pages. To fix:

    • Establish design tokens that define the pairing of primary, secondary, text, and background colors;
    • Write self-check rules for components, e.g., “the contrast between button foreground and background colors should meet the WCAG AA standard (at least 4.5:1 for normal text)”;
    • Check whether form focus, disabled, and error states are complete.
    1. /* styles/tokens.css */
    2. :root {
    3. --color-primary: #2563eb;
    4. --color-on-primary: #ffffff; /* text color on the primary color */
    5. --color-text: #1f2937;
    6. --color-bg: #f9fafb;
    7. --radius-md: 8px;
    8. }
    9. .btn-primary {
    10. background: var(--color-primary);
    11. color: var(--color-on-primary);
    12. }

    Poor Mobile Adaptation

    Forms with broken layouts on narrow screens are the most common experience problem for generated pages. To fix:

    • Use a unified viewport configuration;
    • Adopt flexible layouts and fluid grids;
    • Use relative units and media queries for breakpoints, and check each page at mobile sizes one by one.
    1. .form-row {
    2. display: flex;
    3. flex-wrap: wrap;
    4. gap: 12px;
    5. }
    6. .form-row > * { flex: 1 1 240px; } /* wraps automatically when space is insufficient */

    Incomplete Validation and Error Handling

    AI often generates only “required field” validation, missing boundary and asynchronous error handling. Add a unified async form-validation hook that covers debouncing, race conditions, and retry on failure:

    1. // hooks/useAsyncValidate.ts
    2. import { useEffect, useRef, useState } from 'react';
    3. export function useAsyncValidate<T>(
    4. value: T,
    5. validator: (v: T) => Promise<string | null>,
    6. delay = 300,
    7. ) {
    8. const [error, setError] = useState<string | null>(null);
    9. const [validating, setValidating] = useState(false);
    10. // track the latest request and discard stale results to avoid "a slow request overwriting new input"
    11. const seq = useRef(0);
    12. useEffect(() => {
    13. const current = ++seq.current;
    14. setValidating(true);
    15. const timer = setTimeout(async () => {
    16. try {
    17. const msg = await validator(value);
    18. if (current === seq.current) setError(msg);
    19. } catch {
    20. if (current === seq.current) setError('Validation service is temporarily unavailable, please try again later');
    21. } finally {
    22. if (current === seq.current) setValidating(false);
    23. }
    24. }, delay);
    25. return () => clearTimeout(timer);
    26. }, [value, validator, delay]);
    27. return { error, validating };
    28. }

    All Product Images Are Placeholders

    This is normal at the demo stage; the key is not to let placeholder images become “hardcoded” into business logic:

    • Keep image URLs configured at the data layer so they can be replaced in bulk;
    • Add fallback logic in the image component for load failures;
    • For the above-the-fold main image, consider lazy loading and appropriately sized responsive images to balance load speed.

    Slow Development Iteration

    When the task grows and the context gets longer, some tools’ single-turn response time increases noticeably. Ways to cope:

    • Break a big task into several small ones, e.g., “finish the detail and checkout pages first, then the user center”;
    • Create a conventions file for the project (tech stack, directory standards, coding rules) so the tool can align quickly;
    • Fix the session and rule configuration to reduce the cost of repeating instructions each time.

    For projects where the same problems keep recurring, consider a coding agent with richer model capabilities. For example, DuMate, a general-purpose coding agent from Baidu AI Cloud, can be used in development stages like requirement analysis, code generation, and troubleshooting. Actual results should still be validated against your own project.

    5. Engineering Governance: Bringing AI Output into a Quality System

    AI is responsible for fast output; the quality system is responsible for validation as a safety net—neither can be missing. Introduce at least these four gates.

    Type Checking and Code Standards

    Enable type checking and linting in pre-commit checks to catch and fix problems like type errors and unused variables early.

    Unit Tests

    Prioritize tests for core logic, such as cart amount calculation, coupon deduction, and order state transitions. Because the data access layer is already decoupled, this logic can be tested independently of the UI. The example below covers integer amounts, boundary conditions, and floating-point pitfalls:

    1. // stores/cart.test.ts
    2. import { describe, expect, it } from 'vitest';
    3. import { cartReducer, initialCart } from './cart';
    4. describe('Cart amount calculation', () => {
    5. it('sums product amounts in cents', () => {
    6. const state = cartReducer(initialCart, {
    7. type: 'ADD',
    8. payload: { productId: 'p1', priceCents: 1990, quantity: 2 },
    9. });
    10. expect(state.totalCents).toBe(3980);
    11. });
    12. it('quantity cannot be 0 or negative', () => {
    13. const state = cartReducer(initialCart, {
    14. type: 'ADD',
    15. payload: { productId: 'p1', priceCents: 1990, quantity: 0 },
    16. });
    17. expect(state.totalCents).toBe(0);
    18. });
    19. it('floating-point summation introduces precision errors', () => {
    20. // 19.9 + 19.9 = 39.800000000000004 !== 39.8
    21. expect(19.9 + 19.9).not.toBe(39.8);
    22. });
    23. });

    End-to-End Smoke Tests

    Cover the main flow “register → login → browse products → checkout → view orders” to prevent local changes from breaking the overall flow.

    Continuous Integration Pipeline

    Automatically run checks, tests, and builds on commit or merge. A sample configuration (format similar to common CI config):

    1. stages:
    2. - check
    3. - test
    4. - build
    5. type-check:
    6. stage: check
    7. script:
    8. - npm ci
    9. - npm run type-check
    10. - npm run lint
    11. unit-test:
    12. stage: test
    13. script:
    14. - npm test -- --coverage
    15. build:
    16. stage: build
    17. script:
    18. - npm run build
    19. artifacts:
    20. paths:
    21. - dist/

    6. From Demo to Usable: Deployment and Operations

    Once the frontend project is generated, how to make it truly “live and usable” is also part of the AI-collaboration workflow:

    • Static asset hosting: Build artifacts can be deployed to object storage with CDN acceleration. With the static website hosting capability of Baidu AI Cloud’s object storage BOS, you can host frontend pages directly and use the image processing service to resize and convert product images, reducing the impact of large images on load speed.
    • Route fallback: A single-page application needs a “fall back to the entry page when a path isn’t found” rule; otherwise, directly accessing a secondary route returns 404.
    • Environment variable management: Inject API endpoints, mock toggles, etc. through build-time environment variables, using different configs for different environments.
    • API authentication: User-center data APIs must verify login state and resource ownership on the server. Hiding entries on the frontend is only an experience-level measure and cannot replace server-side permission checks.
    • Observability: Integrate logging and monitoring alerts, and report page exceptions and API errors from the frontend to quickly detect production issues.

    7. How to Evaluate AI Coding Tools

    In practice, developers often try multiple intelligent coding tools at once but struggle to reach objective conclusions. A more reliable approach is a “standardized task + unified scoring dimensions” evaluation method that tests different tools under the same conditions.

    Evaluation Design

    • Fixed task set: Use this article’s e-commerce frontend as the baseline task, supplemented with scenarios like bug fixing, writing unit tests, and refactoring;
    • Unified acceptance cases: Write an acceptance checklist in advance and verify each item manually;
    • Record objective data: Including first-run success rate, manual fix time, total completion time, and number of console errors.

    Scoring Dimensions

    Dimension What to Observe
    Task completion Requirement coverage, whether the shopping flow works end to end
    Code quality Clear layering, complete types, decoupled data
    UI quality Color standards, mobile responsiveness, complete form states
    Interaction and execution mode Whether whole-generation or step-by-step execution suits the task better; whether multi-agent collaboration adds interference
    Response speed Single-turn response time; whether it slows noticeably under long context
    Debugging and fixing Whether it can fix issues on its own based on errors; whether repeated manual intervention is needed
    Data compliance Whether privacy mode is available, whether code is used for training, whether enterprise-grade data protection is supported

    It’s worth noting especially that “more modes isn’t necessarily better.” When a tool offers multiple switchable agents or execution modes, users need to understand the division of labor among modes and pick the one responsible for overall planning and code delivery; otherwise they may end up switching back and forth among roles, which actually slows progress.

    Conclusion: No Single Best, Only Best Fit

    Different tools have different strengths: some have friendly UI guidance and a higher first-pass success rate; some match mainstream editor conventions and offer a privacy mode; some execute fast but need more fix rounds on complex pages. Enterprises should evaluate comprehensively based on their own tech stack, data compliance requirements, and budget, rather than simply using “generation speed” as the sole criterion.

    Conclusion

    AI coding tools have dramatically lowered the cost of going “from 0 to 1,” but going “from 1 to usable” still requires developers to guard quality. For a project like an e-commerce frontend, what truly determines delivery quality is often not how much code the model generated in one pass, but three things:

    1. Whether the requirements are described clearly enough;
    2. Whether architecture and data contracts are agreed upon in advance;
    3. Whether the quality system covers type checking, testing, and continuous integration.

    Treat AI as an efficient executor and engineering standards as the steering wheel. With tools like Baidu AI Cloud’s coding assistant and cloud infrastructure capabilities, developers can efficiently complete the entire journey from idea to launch.