Engineering Practices for Building an E-commerce Front End with AI Coding Tools
This guide explains how to use AI coding tools to build a front-end e-commerce site. It covers page planning and routing, a project structure that separates pages, components, services, and mock data, centralized form validation, responsive layout, image placeholders, and a staged workflow for AI-assisted development. It is written for developers who want generated code to stay organized, easy to maintain, and ready to connect to real services.
1. Background and Problem Definition
As AI coding tools become part of daily development, more teams describe their requirements in natural language and let the tools generate pages, components, and business logic directly. This approach can shorten prototyping cycles, but the quality of the output varies widely. Some projects run on the first attempt. Others need repeated fixes before they start. Some have complete page structures but lack detail polish.
Judging whether an AI-assisted project is successful should not rely only on whether the page renders. Three questions matter more: Is the project structure clear? Can mock data be replaced with real services later? Do the pages work across different devices and in error states?
This article uses a complete front-end e-commerce site as an example. The scope covers the following pages:
- Product detail page
- Checkout page and order success page
- Login and registration pages
- User center, including the dashboard, orders, wallet (coupons and vouchers), and settings
2. Requirement Breakdown: Define the Page List First, Then the Routes
Asking a tool to generate an entire site in one request often produces a disorganized project. A safer approach is to write a page list first. For each page, define four items: entry point, data dependencies, key actions, and error states.
| Page | Core data | Key actions | Error states |
|---|---|---|---|
| Product detail page | Product information, images, stock | Select specifications, add to cart | Product not found, product unlisted |
| Checkout page | Shipping information, order amount | Submit order | Insufficient stock, form errors |
| Order success page | Order number | View order | Missing order number |
| Login page | None | Submit account and password | Wrong account or password, network error |
| Registration page | None | Submit registration details | Invalid fields, account already exists |
| User center | User profile, order list, vouchers | Switch sub-pages, edit settings | Data loading failure, empty list |
Routes should map one-to-one to the page list. Sub-pages under the user center should share one layout, along with the sidebar navigation and user state. This avoids repeating the same framework code on each page.
3. Project Structure Design
A clear structure makes code easier to locate for both AI tools and human developers. Organize directories by responsibility:
src/pages/ Page-level components, one file per routecomponents/ Reusable UI components, such as product cards and form inputsservices/ Data access layer, wrapping all API and mock data callsmocks/ Mock data, separated from business codestyles/ Global styles, theme variables, and shared stylesutils/ Pure functions such as form validation and price formatting
The core principle is this: pages only compose, the service layer decides where data comes from, and styles and themes are managed in one place. If pages hardcode data or styles, moving to a real service later will require changes across many files.
4. Decoupling the Data Layer from the View
Mock data mixed into business code is the most common problem in prototype projects. The fix is to put mock data in an independent module and let the service layer control the data source.
The mock data file stores only data structures:
// mocks/products.jsexport const products = [{id: 1001,name: "Sample Product A",price: 199,stock: 20,images: ["/images/products/1001-main.webp"],description: "Product description for demonstration.",},];
The service layer provides a unified call interface, so pages do not need to know where the data comes from:
// services/productService.jsconst USE_MOCK = true; // Injected by the build config. Set to false in production.export async function fetchProduct(id) {if (USE_MOCK) {const { products } = await import("../mocks/products.js");const item = products.find((p) => p.id === Number(id));if (!item) {throw new Error("Product not found");}return item;}const res = await fetch(`/api/products/${id}`);if (!res.ok) {throw new Error(`Request failed with status ${res.status}`);}return res.json();}
This approach has two benefits. First, switching to a real service only requires changes in the service layer, and page code stays mostly unchanged. Second, the service layer throws errors in a consistent way, so pages can handle loading failures and empty data in one place instead of writing separate checks on each page.
5. Form Validation Design
The login, registration, and checkout pages all contain forms. Validation rules should be defined in one place, not scattered across event handlers on each page.
// utils/validate.jsconst rules = {phone: (v) =>/^1[3-9]\d{9}$/.test(v) ? true : "Please enter a valid 11-digit phone number",password: (v) =>v.length >= 8 && /[A-Za-z]/.test(v) && /\d/.test(v)? true: "Password must be at least 8 characters and contain both letters and numbers",confirm: (v, form) =>v === form.password ? true : "The two passwords do not match",};export function validate(form) {const errors = {};for (const key of Object.keys(rules)) {const result = rules[key](form[key] ?? "", form);if (result !== true) {errors[key] = result;}}return errors;}
Call validate once before submitting. If the returned object is not empty, show each error message below its matching field and block the submission.
Front-end validation only improves the user experience. It cannot replace server-side validation. Client-side rules can always be bypassed, so the server must validate the same fields again. Passwords should also be stored as hashes, never in plain text.
6. Interface and Responsive Layout
Common interface problems in prototype projects include misaligned layouts on mobile, button colors that clash with the background, and forms that break on narrow screens. Most of these can be solved with consistent layout rules and a color system.
/* styles/layout.css */*,*::before,*::after {box-sizing: border-box;}.container {max-width: 1200px;margin: 0 auto;padding: 0 16px;}.product-grid {display: grid;grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));gap: 16px;}.auth-form {width: 100%;max-width: 400px;margin: 40px auto;}.btn-primary {background: #0a6cff;color: #ffffff;border: none;padding: 10px 20px;border-radius: 4px;}@media (max-width: 768px) {.product-grid {grid-template-columns: repeat(2, 1fr);}}@media (max-width: 375px) {.product-grid {grid-template-columns: 1fr;}}
Three points about this stylesheet are worth noting.
First, box-sizing: border-box keeps input fields from overflowing their containers when padding is added. This is a common cause of distorted forms.
Second, the form container uses max-width instead of a fixed width, so it shrinks automatically on narrow screens.
Third, color contrast must be checked separately. For normal text, the contrast ratio between button text and its background should be at least 4.5:1. For large text, the minimum is 3:1. If the button text and background colors are too close, users may not be able to read the label. A general-purpose contrast checker can confirm during the design stage that the colors meet these thresholds, rather than uncovering the problem after launch.
7. Image Resources and Placeholder Strategy
If every product image is a placeholder, the detail page loses its persuasive power. Placeholder images are acceptable during development, but the following practices keep the cost of later replacement as low as possible.
<imgsrc="/images/products/1001-main.webp"alt="Sample Product A main image"width="800"height="800"loading="lazy"/>
- Set explicit width and height for every image so the browser can reserve space and avoid content shifting during loading.
- Use
alttext to describe each image. This supports accessibility and displays when an image fails to load. - Lazy-load images that are not in the first viewport to reduce the number of requests on initial load.
- Have the data layer provide image paths, and name files with the product ID and purpose so they can be replaced in bulk.
Actual image storage is usually handled by an object storage service, and the front end only stores the access URL. This lets dedicated infrastructure handle image upload, distribution, and caching.
8. Working Method for AI-Assisted Development
AI coding tools can significantly reduce the time spent on repetitive coding, but their output still needs review. The following methods help control quality.
Provide requirements in stages. First, have the tool generate the project skeleton and routes. Then implement each page one at a time. Finally, add APIs and styles. Requesting the entire site in one prompt often produces disorganized code with missing details. In practice, the larger the task, the lower the success rate of a single generation.
Set explicit constraints. Specify the directory structure, naming rules, and prohibited actions in the requirements. For example: “Mock data must be placed in the mocks directory. Page components must not hardcode data.” The more specific the constraints, the more stable the output.
Verify after each round. After each generation, run the project, check the console for errors, and walk through the main flow of each page.
