Building an AI-Assisted E-Commerce Frontend: Consistency and Completeness Practices
This article explains how to build a multi-page e-commerce frontend with AI assistance while maintaining flow completeness, visual consistency, and engineering consistency. It covers route planning, data and view separation, design tokens, form validation, responsive layout, order state transitions, acceptance checks, and an iterative delivery strategy.
1. Why E-Commerce Sites Demand More from Generated Code
An e-commerce site consists of multiple pages that share login state, product data, order information, and inventory data. A single page working correctly does not mean the whole site is usable. Common issues in generated code include inconsistent page styles, insufficient contrast between button text and background, broken route links, inconsistent field names for the same entity across pages, and duplicate nested project directories.
Whole-site quality can be evaluated on three levels:
- Flow completeness: Whether the full path from browsing products to successful payment works, and whether exception branches such as unauthenticated access, insufficient inventory, and form errors provide clear feedback.
- Visual consistency: Whether fonts, colors, spacing, border radius, and button styles are consistent, and whether layouts work on both mobile and desktop.
- Engineering consistency: Whether directory structure, naming conventions, data sources, and style organization are unified, and whether later changes are easy to locate.
Among these three levels, flow completeness is the easiest to overlook. Generation tools can often produce a single page quickly, but cross-page state passing requires manual verification item by item.
2. Page Inventory and Information Architecture
Ten pages can be divided into three groups by responsibility:
- Public browsing group: Home page (product list page) and product detail page.
- Transaction group: Checkout page and purchase success page.
- Account group: Login page, registration page, and user center (dashboard, orders, wallet and coupons, settings).
Information architecture should be defined before code. It is recommended to use a route table to fix page paths and access permissions, and use that table as the source of truth during code generation so that pages do not define paths independently.
const routes = [{ path: '/', page: 'ProductList', auth: false },{ path: '/product/:id', page: 'ProductDetail', auth: false },{ path: '/checkout/:productId', page: 'Checkout', auth: true },{ path: '/checkout/success/:orderId', page: 'CheckoutSuccess', auth: true },{ path: '/login', page: 'Login', auth: false },{ path: '/register', page: 'Register', auth: false },{ path: '/account', page: 'Dashboard', auth: true },{ path: '/account/orders', page: 'Orders', auth: true },{ path: '/account/wallet', page: 'Wallet', auth: true },{ path: '/account/settings', page: 'Settings', auth: true },];
The route guard reads the auth field consistently. When an unauthenticated user accesses a page that requires authentication, redirect them to the login page and return them to the original address after successful login. This rule is written once and shared by all protected pages, which prevents some pages from missing authentication checks.
3. Separating the Data Layer from the View Layer
Using mock data early in a project is reasonable, but mock data should not be written directly inside components. Once a component is coupled to data, replacing it with a real API requires changes on every page, making the scope of modification difficult to control.
A recommended approach is to split data into three layers: raw data files, service-layer functions, and view components. View components call only the service layer and do not read data files directly.
// data/products.js: mock data onlyexport const products = [{ id: 'p001', name: 'Sample Product A', price: 199, stock: 20, images: ['/img/p001-1.jpg'] },{ id: 'p002', name: 'Sample Product B', price: 89, stock: 0, images: ['/img/p002-1.jpg'] },];// services/productService.js: unified external interfaceconst delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));export async function fetchProducts() {await delay(300);return products;}export async function fetchProductById(id) {await delay(300);return products.find((p) => p.id === id) ?? null;}
The benefit is that replacing mock data with a real API requires changing only the service-layer implementation, not the page components. The return structure of service-layer functions should match the real API, including empty values and error cases. Images in mock data should use real accessible resources or a centralized placeholder rule. Large areas of placeholders can hide layout problems and cause the team to misjudge the real appearance of the page.
4. Design Tokens and Style Consistency
The key to page consistency is centralized management of visual parameters. Colors, spacing, border radius, and font sizes should be defined as design tokens, and pages should reference only tokens rather than hard-coded values.
:root {--color-primary: #2563eb;--color-on-primary: #ffffff;--color-surface: #f8fafc;--color-text: #0f172a;--space-2: 8px;--space-4: 16px;--radius-md: 8px;}.btn-primary {background: var(--color-primary);color: var(--color-on-primary);padding: var(--space-2) var(--space-4);border-radius: var(--radius-md);}
Color combinations need separate validation. The contrast between button text and background should meet readability requirements; for normal text, contrast is generally no lower than 4.5:1. A common issue in generated code is that button text and background use the same or similar colors, making the text invisible. Before a build, scan the main combinations with a contrast-checking tool, or verify them item by item during code review.
5. Form Validation
Validation rules for the login and registration pages need to remain consistent between the frontend and the server. Frontend validation provides immediate feedback, while server-side validation enforces the security boundary. The two cannot replace each other.
Validation functions should be written as pure functions that take form data as input and return an error object, making them easy to unit test.
export function validateRegister(form) {const errors = {};if (!/^[\w.-]+@[\w-]+\.[\w.]+$/.test(form.email)) {errors.email = 'Invalid email format';}if (form.password.length < 8) {errors.password = 'Password must be at least 8 characters';}if (form.password !== form.confirmPassword) {errors.confirmPassword = 'Passwords do not match';}return errors;}
Validation rules should cover required fields, format, length, matching of repeated input, and duplicate-submit protection during submission. Error messages should be displayed next to the corresponding field, not only as a single notification at the top. After successful submission, the submit button should be disabled until the request completes or fails.
6. Responsive Layout
The main traffic for e-commerce sites comes from mobile devices, so layouts should follow a mobile-first approach: ensure narrow screens are usable first, then gradually add wider-screen arrangements.
.container {width: 100%;max-width: 1200px;margin: 0 auto;padding: 0 16px;}.product-grid {display: grid;grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));gap: 16px;}.auth-form {max-width: 400px;margin: 0 auto;padding: 24px;}@media (max-width: 600px) {.auth-form {padding: 16px;}}
Fixed widths are a common cause of layout breakage. Login and registration forms should use a maximum width instead of a fixed width, and images should use adaptive aspect ratios to avoid overflow on narrow screens. During acceptance, check each page at multiple viewport widths and confirm that there is no horizontal scrollbar.
7. State Consistency in the Purchase Flow
The purchase flow involves multiple data objects such as products, inventory, orders, and payment results. When state management is unclear, the most common error is that the order page shows paid while the purchase success page still shows pending payment.
It is recommended to define an explicit set of order statuses and allowed status transitions, and to have all pages modify state through the same function.
const ORDER_STATUS = {PENDING: 'pending',PAID: 'paid',CANCELLED: 'cancelled',};const transitions = {pending: ['paid', 'cancelled'],paid: [],cancelled: [],};export function canTransition(from, to) {return (transitions[from] || []).includes(to);}
Inventory deduction should follow the same principle. The inventory shown on the product detail page, the inventory used when placing an order on the checkout page, and the inventory used when creating the order must come from the same data source. Inventory should be validated again before placing an order to avoid inconsistency between the page display and the actual result. The purchase success page should read order data by order ID rather than relying on temporary state passed between pages, because temporary state is lost when the user refreshes the page.
8. Acceptance Checklist
Before delivering the whole site, verify the following items one by one:
- The build and startup complete without errors, and the console has no unhandled exceptions.
- All paths in the route table can be accessed directly, and refreshing the page does not return 404. A single-page application needs server-side fallback configuration to the entry file.
- When an unauthenticated user accesses a protected page, the user is correctly redirected to the login page and returned to the original page after login.
- At mobile and desktop widths, no page has horizontal overflow.
- Button text and background contrast meet readability requirements.
- Field names for the same entity, such as products and orders, are consistent across all pages.
- The directory structure has no duplicate nested folders with the same name.
- Mock data is separated from styles and components, and replacing the data source requires no changes to page components.
- In the purchase flow from order placement to successful payment, the order page and success page show consistent states.
9. Iteration Strategy
Generating the entire site in one pass is risky, and errors are difficult to locate. A more reliable approach is to proceed in stages:
- Define the project specification first, including the page inventory, route table, data models, and design tokens.
- Set up the directory structure and route skeleton, and confirm that the whole site starts and switches pages correctly.
- Implement shared components such as the navigation bar, footer, product cards, and form controls.
- Implement pages group by group, and run integration checks after each group is complete.
- Finally, review styles, responsive layouts, and exception branches in a unified pass.
When an error occurs, locate the root cause first, such as a missing dependency, incorrect path, inconsistent import name, or uninitialized state, rather than repeatedly asking the generation tool to rewrite the entire project. After each fix, rerun the full checks to confirm that no new issues have been introduced. The specification document should be updated alongside the code and serve as the basis for later changes and team collaboration.
