Building an E-commerce Frontend from Scratch with AI-Assisted Programming

    This article explores the transition of AI-assisted programming from single-file completion to full-site generation for e-commerce frontends. It details practical strategies for requirement breakdown, consistency validation, form validation, data decoupling, and project structure. Additionally, it provides a comprehensive runnability verification process and an evaluation checklist to ensure the generated code is ready for integration and delivery.

    1. Why Focus on Full-Site Generation Quality

    AI-assisted programming is shifting from single-file completion to the overall generation of multi-page and multi-module architectures. For projects like e-commerce sites that contain over a dozen pages, the value of generation tools depends on whether the results can form a runnable, stylistically unified, and data-connected whole, rather than just several isolated pages. Therefore, the evaluation focus should shift from “can it generate a page” to “can it be delivered after generation.”

    Before delivery, three questions must be answered: Can pages navigate smoothly between each other? Is the same business data consistent across different pages? Can the code structure support future iterations? The following sections revolve around these three questions.

    2. Page Scope and Requirement Breakdown

    A basic e-commerce frontend typically includes three categories of pages.

    1. Public browsing pages: Homepage product list, product detail page.
    2. Transaction flow pages: Product purchase page, purchase success page.
    3. Account and user center: Login page, registration page, user dashboard, orders page, wallet or coupon page, settings page.

    Before generation, requirements should be broken down into verifiable specifications, clarifying at least the following:

    • Navigation relationships and entry conditions between pages;
    • How login status is determined and which pages require authentication;
    • Enumerated values for order status (e.g., pending payment, paid, shipped, completed, canceled);
    • Field definitions for core data like products, users, and orders.

    The ordering process can be described as follows for mutual reference between the generation tool and manual acceptance:

    1. Product Detail Page -> Purchase Page (Select specs and quantity) -> Submit Order -> Purchase Success Page
    2. ↘ Unlogged -> Login Page -> Return to Purchase Page after login

    The more specific the specifications, the lower the probability of the generated result deviating from expectations. Conversely, giving a prompt like “make a shopping site” makes it difficult to control the page count and business details.

    3. Acceptance Dimensions for Completeness and Overall Consistency

    Overall site consistency can be broken down into four checkable dimensions.

    1. Route Completeness: Every page must be directly accessible via its URL. Unauthenticated users accessing pages requiring authentication should be redirected to the login page and return to the original page after logging in.
    2. Visual Consistency: Styles like colors, font sizes, spacing, and border radii should come from the same set of design tokens to prevent each page from defining its own color values. An example is as follows:
    1. :root {
    2. --color-primary: #2563eb;
    3. --color-text: #1f2937;
    4. --color-text-muted: #6b7280;
    5. --color-danger: #dc2626;
    6. --spacing-base: 8px;
    7. --radius-card: 8px;
    8. }
    9. .btn-primary {
    10. background: var(--color-primary);
    11. color: #ffffff;
    12. padding: calc(var(--spacing-base) * 1.5) calc(var(--spacing-base) * 3);
    13. border-radius: var(--radius-card);
    14. }
    1. Responsive Adaptation: Breakpoints should be defined in advance, for example, below 768 pixels for mobile layout and 768 pixels and above for desktop layout. Form pages like login and registration are prone to element distortion on narrow screens and require separate checks.
    2. State Consistency: Information like cart item count, user nickname, and order status is displayed across multiple pages. When modified on any page, other pages should sync the update or read the latest value upon the next entry.

    During acceptance, it is recommended to open each page under both desktop and mobile widths and record any deviations.

    4. Form Validation Design

    A common issue with form validation is that rules are scattered across various components, causing the same field to have inconsistent rules on the registration page and in the user center. The correct approach is to centrally define validation rules and reuse them across pages.

    1. // validation/rules.js
    2. export const rules = {
    3. username: [
    4. { required: true, message: 'Please enter your username' },
    5. { pattern: /^[a-zA-Z0-9_]{4,16}$/, message: 'Username must be 4-16 characters of letters, numbers, or underscores' },
    6. ],
    7. phone: [
    8. { required: true, message: 'Please enter your phone number' },
    9. { pattern: /^\+?[1-9]\d{1,14}$/, message: 'Invalid phone number format' },
    10. ],
    11. password: [
    12. { required: true, message: 'Please enter your password' },
    13. { minLength: 8, message: 'Password must be at least 8 characters' },
    14. ],
    15. };
    16. // validation/validateField.js
    17. export function validateField(value, fieldRules) {
    18. for (const rule of fieldRules) {
    19. if (rule.required && !value) return rule.message;
    20. if (rule.minLength && value.length < rule.minLength) return rule.message;
    21. if (rule.pattern && value && !rule.pattern.test(value)) return rule.message;
    22. }
    23. return null;
    24. }

    When implementing, three points require attention:

    • Validation timing: Validate single fields on blur and the entire form on submit. Combining both balances user experience and interception rate.
    • Error prompts: Error messages should point to specific fields and explain how to correct them.
    • Server-side validation: Frontend validation only improves the experience and cannot replace server-side validation. APIs for registration, payment, etc., must be re-validated on the server.

    5. Decoupling Data from UI

    Hardcoding mock data directly into page components is a common issue in generated code. It leads to two consequences: page-by-page modifications are required when connecting real APIs, and page logic becomes tightly bound to data structures, making testing difficult.

    The recommended approach is a three-layer organization: the data layer provides mock data, the API layer encapsulates requests, and the page layer only calls the API layer.

    1. // data/products.js
    2. export const mockProducts = [
    3. {
    4. id: 'p1001',
    5. name: 'Sample Product A',
    6. price: 129.0,
    7. stock: 20,
    8. image: '/images/products/p1001.jpg',
    9. },
    10. ];
    11. // api/product.js
    12. import { mockProducts } from '../data/products';
    13. const USE_MOCK = true; // Switch to false during API integration
    14. export async function fetchProducts() {
    15. if (USE_MOCK) {
    16. return mockProducts;
    17. }
    18. const response = await fetch('/api/products');
    19. if (!response.ok) {
    20. throw new Error(`Request failed: ${response.status}`);
    21. }
    22. return response.json();
    23. }

    This way, during integration, you only need to toggle the switch in the API layer without altering the page code. The same logic applies to order, user, and wallet data.

    6. Image Assets and Placeholder Handling

    Using placeholders for all images makes the product detail page unconvincing and fails to verify whether the layout works normally under real content. It is recommended to establish these standards early in the project:

    • Aspect ratio: Product list images should uniformly be 1:1, and detail main images should uniformly be 4:3 to prevent grid distortion caused by different image ratios.
    • Loading method: List page images should use lazy loading to reduce first-screen requests.
    • Failure fallback: Display a unified default image on load failure and retain the original image area size to prevent page layout shifts.
    1. function ProductImage({ src, alt }) {
    2. // Use a unified default image on load failure
    3. return (
    4. <img
    5. src={src}
    6. alt={alt}
    7. loading="lazy"
    8. onError={(event) => {
    9. event.currentTarget.src = '/images/placeholder.png';
    10. }}
    11. />
    12. );
    13. }

    A clearly structured project facilitates subsequent maintenance and helps evaluate the architectural quality of the generated result. A suitable directory division for small to medium e-commerce frontends is as follows:

    1. src/
    2. pages/ Page-level components, each corresponding to a route
    3. components/ Common components, such as buttons, form items, product cards
    4. api/ API request encapsulation
    5. data/ Mock data, keeping the same data structure as the API layer
    6. validation/ Form validation rules
    7. styles/ Global styles and design tokens
    8. hooks/ Custom logic reuse modules, added only when there is a real reuse need
    9. store/ Cross-page shared state, such as login info and cart

    The existence of a directory does not mean it has content. If a directory is just an empty shell, it should be deleted or its implementation completed. Empty directories can mislead people into thinking a feature is finished and are easily overlooked during acceptance.

    8. Runnability Verification Process

    Whether the generated result can run requires checking via a fixed process, rather than just looking at page screenshots.

    1. Dependency Installation and Startup: Execute installation and startup commands according to the project instructions; passing in one go is acceptable.
    2. Console Check: Open the browser console after startup; there should be no runtime errors. Warning messages need to be evaluated individually to determine if they affect functionality.
    3. Main Flow Walkthrough: From the homepage to product details, place an order after selecting specs, passing through login or registration, and finally reaching the purchase success page. There should be no dead links or data loss in between.
    4. Exception Path Check: Test unauthenticated access, form input errors, API returning empty data, and image load failures separately. Pages should provide clear prompts or fallbacks.
    5. Responsive Check: Check the layout under narrow and wide screens, focusing on the form areas of login, registration, and purchase pages.

    9. Common Issues and Handling Principles

    When the generated result throws errors, avoid repeatedly regenerating the entire project. A more effective method is:

    • Start locating from the first error. Errors often have causal relationships; fixing upstream errors often eliminates subsequent ones.
    • Provide the error messages along with the relevant files to reduce missing context.
    • Re-test the main flow immediately after each fix to prevent fixing one thing while breaking another.

    Style issues are mostly related to color contrast. The contrast ratio between text and background colors should meet common readability standards, with body text not less than 4.5:1. Issues like white text on a white background or dark text on a dark background can be avoided by managing colors uniformly through design tokens.

    Business logic gaps usually occur in order status transitions and wallet deductions. Before development, agree on API contracts, including request parameters, response structures, and error codes. When generating code, adhere to the contract rather than relying on the generation tool’s own inference.

    10. Evaluation Checklist

    To evaluate the quality of a full-site generation, you can score each item below:

    • All ten pages are accessible, and the main flow is completely functional;
    • Login status applies to pages requiring authentication, with the ability to return to the original page after login;
    • Colors, font sizes, and spacing come from unified design tokens;
    • Both desktop and mobile layouts are usable, with no obvious distortion on form pages;
    • Form validation rules are centrally defined, effective on both blur and submit;
    • Mock data is separated from page components, with switchable APIs;
    • Images have a unified aspect ratio, loading method, and failure fallback;
    • No empty shell modules exist in the directory structure;
    • No runtime errors in the console.

    A project that passes item by item has the foundation to enter real API integration.