AI-Assisted Frontend Development: Building an E-Commerce Application from Scratch

    This guide explains how to use AI coding tools to build a maintainable e-commerce frontend. It covers requirement decomposition, iterative generation, project architecture, mock data, form validation, responsive design, image handling, shopping-flow state management, error troubleshooting, and delivery checks.

    1. Background and Problem Definition

    An e-commerce frontend may appear to contain only a few pages, but it actually combines several subsystems, including product presentation, purchasing, user authentication, and account management. A minimum viable storefront typically includes:

    • Product detail
    • Checkout
    • Purchase success
    • Login
    • Registration
    • User dashboard
    • Order list
    • Coupon or voucher wallet
    • Account settings

    These pages are connected through routing, authentication checks, and shared data. If any link in the chain is missing, the shopping journey cannot be completed.

    When AI-assisted coding tools are used to build this type of project, the most common problems include the following.

    First, visual quality is inconsistent. Generated interfaces may be functional, but their color systems are often poorly coordinated. Button text may have insufficient contrast, and some components may even use white text on a white background.

    Second, mobile responsiveness is frequently overlooked. Many pages are generated for desktop widths, causing forms to deform and elements to overflow on smaller screens. Fixed-width containers are especially problematic on login and registration pages.

    Third, form validation is incomplete. Validation needs to cover required fields, formats, length limits, and confirmation fields. Generated code often misses edge cases.

    Fourth, images and data are not always structured properly. Placeholder images can hide real layout problems, while mock data placed directly inside components makes later API integration unnecessarily difficult.

    Fifth, generated projects often fail on their first run. Large one-shot outputs may contain complex dependencies, incorrect import paths, or inconsistent types. Repeatedly asking the tool to rewrite code without a troubleshooting method can introduce additional problems.

    The central question, therefore, is how to improve development efficiency while keeping the generated project runnable, clearly structured, and maintainable.

    2. Break Down Requirements Before Generating Code

    Before asking an AI tool to generate code, convert the requirements into a structured checklist. At a minimum, the checklist should cover pages, routes, state, and data.

    For example:

    1. Pages: Product detail, checkout, purchase success, login, registration, user center
    2. (dashboard, orders, coupons, settings)
    3. Routes: /product/:id, /checkout, /checkout/success, /login, /register, /user/*
    4. Global state: Authentication status, shopping cart, current user
    5. Data services: Product details, order creation, order list, coupon list, user profile

    This checklist limits the scope of generation. Without clear boundaries, an AI tool may add unrequested features such as extra payment methods or marketing modules, increasing maintenance costs. The checklist also makes acceptance testing easier because every feature can be verified individually.

    Non-functional requirements should also be specified. These may include target screen sizes, primary and secondary colors, image aspect ratios, and the format of form error messages. The more specific these conventions are, the smaller the gap between the generated result and the intended design.

    3. Two Collaboration Models: One-Shot Generation and Iterative Development

    Two collaboration models are common in practice.

    One-Shot Generation

    In this model, the complete requirements are provided and the tool generates the entire project in one pass. The main advantage is speed. It is useful for quickly producing a page skeleton or visual prototype.

    The disadvantage is that all module dependencies are created at once. A single incorrect import path or inconsistent type can prevent the entire project from starting. When errors occur, they may be distributed across multiple files, making diagnosis more difficult.

    Iterative Development

    In an iterative workflow, development proceeds in stages:

    1. Create the project skeleton and configure routing.
    2. Confirm that the project starts successfully.
    3. Implement pages one at a time.
    4. Run and verify the project after each page.
    5. Handle styling and interaction details after the main functionality is complete.

    This approach takes longer, but each change has a smaller scope, making errors easier to locate.

    The two models can be compared by first-run success rate, error-repair cost, maintainability, process control, and total development time. A practical approach is to combine them: use one-shot generation to create the initial skeleton, then use iterative development to complete features and fix issues.

    Regardless of the chosen model, every stage should leave the project in a runnable state. Avoid stacking more changes on top of a project that is already broken.

    4. Project Architecture: Layering Matters More Than Page Count

    Even a medium-sized frontend project should be separated by responsibility. A typical structure looks like this:

    1. src/
    2. pages/ Page-level components for layout and data composition
    3. components/ Reusable business components, such as product cards and order items
    4. services/ Data-access layer containing API calls
    5. mock/ Mock data separated from business logic
    6. styles/ Global variables, base styles, and theme configuration
    7. utils/ Validation rules, formatting functions, and other pure logic
    8. router/ Route configuration and authentication guards

    The core principle is to keep dependency direction simple. Pages may depend on components and services. Components should primarily receive properties, while the service layer should not depend on pages. This structure makes it possible to replace a data source or adjust the visual design without modifying many unrelated files.

    Separating styles from logic is equally important. Store styles in dedicated files and manage colors, spacing, and border radii through shared variables. Visual changes can then be made in one place.

    5. Decouple Mock Data from Business Logic

    Mock data is essential during frontend development, but placing it directly inside a component creates two problems: the component takes on too many responsibilities, and replacing mock data with a real API requires extensive changes.

    A better approach is to centralize data access in the service layer and use configuration to select mock data or a real API.

    1. // src/services/productService.js
    2. import { mockProducts } from '../mock/products';
    3. import { config } from '../config';
    4. export async function fetchProductDetail(id) {
    5. if (config.useMock) {
    6. const item = mockProducts.find((p) => p.id === id);
    7. if (!item) {
    8. throw new Error('Product not found');
    9. }
    10. return structuredClone(item);
    11. }
    12. const res = await fetch(`/api/products/${id}`);
    13. if (!res.ok) {
    14. throw new Error(`Request failed with status: ${res.status}`);
    15. }
    16. return res.json();
    17. }

    This example has three important characteristics.

    First, page components only call fetchProductDetail and do not need to know where the data comes from. Second, mock data and business logic are stored in separate files, so changing the data does not affect the application logic. Third, errors are thrown consistently in the service layer and displayed by the page layer.

    structuredClone returns a deep copy of the data. This prevents a component from accidentally modifying the original mock data and creating hidden side effects.

    6. Form Validation: The Frontend Serves Usability, the Backend Enforces Security

    Form validation should be implemented at two levels. Frontend validation provides immediate feedback and reduces invalid requests. Backend validation ensures data security and consistency. Because frontend checks can be bypassed, the backend must independently enforce the same rules.

    For login and registration, validation rules should be centralized instead of duplicated across multiple pages.

    1. // src/utils/validators.js
    2. const PHONE_REGEX = /^1[3-9]\d{9}$/;
    3. export function validateLogin({ username, password }) {
    4. const errors = {};
    5. if (!username.trim()) {
    6. errors.username = 'Username is required';
    7. }
    8. if (password.length < 8) {
    9. errors.password = 'Password must be at least 8 characters';
    10. }
    11. return errors;
    12. }
    13. export function validateRegister({ phone, password, confirmPassword }) {
    14. const errors = validateLogin({ username: phone, password });
    15. if (!PHONE_REGEX.test(phone)) {
    16. errors.phone = 'Invalid phone number format';
    17. }
    18. if (password !== confirmPassword) {
    19. errors.confirmPassword = 'The passwords do not match';
    20. }
    21. return errors;
    22. }

    The validation functions return an error object instead of displaying messages directly. This allows the page to decide how errors should appear, such as showing text below an input and preventing submission. Pure validation functions are also easier to test independently.

    Boundary cases should be covered as well, including empty or whitespace-only strings, excessively long input, full-width characters, and pasted content containing spaces. These cases are often missed by generated code and should receive dedicated attention during acceptance testing.

    7. Responsive Design and Visual Usability

    For mobile support, a mobile-first strategy is recommended. Start with small-screen styles, then add layouts for larger screens through media queries. Common breakpoints include 768 and 1024 pixels, although the exact values should reflect the target users’ devices.

    Login and registration pages commonly break because their containers use fixed pixel widths, inputs have no maximum width, or padding is too large for small screens. A combination of relative width and maximum width provides a more flexible solution:

    1. :root {
    2. --color-primary: #1a6cf0;
    3. --color-on-primary: #ffffff;
    4. --color-text: #1f2329;
    5. --radius-md: 8px;
    6. }
    7. .auth-card {
    8. width: 100%;
    9. max-width: 420px;
    10. margin: 0 auto;
    11. padding: 24px 16px;
    12. box-sizing: border-box;
    13. }
    14. .btn-primary {
    15. background: var(--color-primary);
    16. color: var(--color-on-primary);
    17. border-radius: var(--radius-md);
    18. }
    19. @media (min-width: 768px) {
    20. .auth-card {
    21. padding: 40px 32px;
    22. }
    23. }

    Color contrast is a foundation of visual usability. Web accessibility guidelines recommend a contrast ratio of at least 4.5:1 for normal-sized text. White text on a white background has a contrast ratio of 1:1, making the content unreadable. When choosing a primary color, also verify the text color displayed on top of it. Shared variables help prevent each component from defining inconsistent colors.

    A friendly interface depends on state feedback as much as on color. Every asynchronous operation should provide a loading state. Empty lists should display an empty-state message, and successful or failed submissions should produce clear feedback. Illustrations and other supporting graphics can make an interface more approachable, but they should be used carefully so that they do not interfere with reading.

    8. Image Assets and Product Details

    Placeholder images can conceal real layout problems. For example, changes in image dimensions after loading can cause layout shifts. Image handling should follow these practices:

    • Use a consistent aspect ratio.
    • Place images in containers with a fixed ratio to prevent layout shifts.
    • Use object-fit behavior to center and crop images instead of stretching them.
    • Lazy-load images that are not above the fold.
    • Provide alternative text for every image so screen readers can describe it.

    Real images are commonly stored in object storage services. The frontend only needs to store their URLs. Databases and mock data should record image paths rather than embedding encoded image content in source code.

    The amount of information on a product detail page directly affects purchase decisions. A complete page commonly includes:

    • An image carousel and thumbnails
    • Price and promotion details
    • Variant selection and inventory status
    • Delivery and after-sales information
    • Product descriptions and specification lists

    Variant selection must handle unavailable combinations. For example, if a particular color and size combination is out of stock, the corresponding option should be disabled and accompanied by an appropriate message.

    9. State Management for the Shopping Flow

    The shopping journey uses shared state across multiple pages, including authentication status, cart contents, and pending order information. This state should be stored centrally, while each page reads and submits only the data it needs.

    Several details are essential to a complete flow:

    • If an unauthenticated user accesses the user center or checkout page, a route guard should redirect them to the login page.
    • After successful login, the user should be returned to the original page.
    • The purchase success page should render based on the order result.
    • Direct access to the success page should be handled safely so that nonexistent order information is not displayed.
    • Order submission should disable repeated clicks to prevent duplicate orders.

    These details are easy to overlook during early development, but they determine whether users can complete a purchase successfully. They should be treated as core acceptance criteria.

    10. A Method for Troubleshooting Errors

    When a project fails to run, blindly asking the AI tool to rewrite the code is usually inefficient. A more reliable process is as follows.

    1. Read the complete error message, including the file path, line number, and call stack. Determine whether the problem involves syntax, an import path, a type mismatch, or runtime logic.
    2. Reproduce the issue in the smallest possible scenario. If a page fails, check whether it depends on unfinished modules. Replace those dependencies with mock data when necessary.
    3. Make only one change at a time and run the project immediately afterward. Simultaneous changes make it difficult to identify the source of the problem.
    4. Save a version-control snapshot after each runnable stage. If a later change introduces a regression, return to the last stable version instead of restarting the investigation.
    5. After fixing an issue, verify that existing features still work. A common frontend problem is unintentionally changing the appearance of global buttons while fixing the styles of a single page.

    11. Delivery Quality Checklist

    Before delivery, review the project against the following criteria.

    Check area Acceptance criteria
    Functional completeness Product detail, checkout, success, login, registration, and all user-center pages are accessible; the shopping flow can be completed
    Form validation Required-field, format, length, and confirmation rules work correctly; error messages are clear
    Mobile responsiveness Common phone widths have no horizontal scrolling; form elements do not deform
    Visual usability Text and backgrounds have sufficient contrast; colors, spacing, and component styles are consistent
    Data architecture Mock data is separated from business logic; data access is centralized in the service layer
    State and routing Authentication guards, return navigation, order rendering, and duplicate-submission prevention work correctly
    Error handling Loading, empty, success, and failure states are clearly communicated
    Maintainability Responsibilities are separated by layer, and the project can be started and modified without unrelated changes