Building an E-Commerce Frontend with AI Programming Tools: Consistency and Runnable Practices

    This article provides a practical guide for engineers who want to build e-commerce frontends using AI programming tools. It covers a complete workflow including route contracts, design tokens, and validation rules for organizing a Vue 3 project with Vite and Node.js 20 LTS. The article defines five acceptance criteria for evaluating generated code, introduces a ten-page routing contract with authentication guards and safe redirects, and explains how to maintain visual consistency through centralized design tokens. It also demonstrates how to separate the data layer from view components using service functions, standardized error codes, and mock data isolation. A checklist is included to help you verify AI-generated results before deployment.

    Introduction

    This article targets engineers who need to build e-commerce frontends with AI programming tools. After reading it, you will be able to organize your project according to the routing contract, design tokens, and validation rules described here, and verify generated results with the acceptance checklist at the end. The examples are based on Vue 3, Vue Router 4, and Vite, with Node.js 20 LTS.

    1. Problem Definition

    An e-commerce site is a typical scenario for testing AI programming capabilities. It includes pages such as product listing, product detail, checkout, checkout success, login, registration, and user center. These pages share navigation, login state, visual guidelines, and data models across the site. Individual pages are not usually difficult to generate; the challenge lies in overall cross-page consistency: whether buttons on different pages look the same, whether login state survives navigation, and whether the order page displays data consistent with what was submitted on the checkout page.

    For acceptance, we recommend evaluating the result across the following five dimensions. Each dimension must have clear pass criteria and supporting evidence.

    Dimension Pass Criteria Evidence
    Completeness All ten pages are accessible, and navigation forms a closed loop A record of visiting each route in the router table one by one
    Consistency Colors, spacing, font sizes, button states, and error messages are uniform No hardcoded color values in pages
    Runnable One-shot startup after installation, build without errors, no blank first screen Build logs and browser console output
    Maintainable Clear directory structure; data, logic, and views are separated Pages do not import mock data directly
    Adaptable Layout works on both narrow and wide screens; forms and cards do not break Screenshots at 375px and 1440px widths

    These five dimensions are independent of specific tools. Regardless of the generation method, acceptance should be based on these standards.

    2. Task Breakdown and Route Contract

    The ten pages can be grouped into four categories: public entry points (home page, product detail), transaction flow (checkout page, checkout success page), account entry (login, registration), and user center (dashboard, orders, wallet, settings).

    The transaction flow requires agreed-upon parameters in advance. The checkout page depends on the product ID and quantity. The checkout success page depends on the order number. Without a unified agreement on these parameters, each page can run independently but will break when connected. Therefore, the router table and parameter contract should be defined before coding.

    Page Path Parameters Requires Login
    Home / None No
    Product Detail /products/:id id from path No
    Checkout /checkout/:id?qty=1 id is the product, qty is the quantity Yes
    Checkout Success /checkout/success/:orderId orderId from path Yes
    Login /login?redirect= redirect is the post-login destination No
    Register /register None No
    User Center (four pages) /account/… None Yes
    1. // src/router/routes.js
    2. export const routes = [
    3. { path: '/', name: 'ProductList',
    4. component: () => import('../pages/ProductListPage.vue'),
    5. meta: { requiresAuth: false } },
    6. { path: '/products/:id', name: 'ProductDetail',
    7. component: () => import('../pages/ProductDetailPage.vue'),
    8. meta: { requiresAuth: false } },
    9. { path: '/checkout/success/:orderId', name: 'CheckoutSuccess',
    10. component: () => import('../pages/CheckoutSuccessPage.vue'),
    11. meta: { requiresAuth: true } },
    12. { path: '/checkout/:id', name: 'Checkout',
    13. component: () => import('../pages/CheckoutPage.vue'),
    14. meta: { requiresAuth: true } },
    15. { path: '/login', name: 'Login',
    16. component: () => import('../pages/LoginPage.vue'),
    17. meta: { requiresAuth: false } },
    18. { path: '/register', name: 'Register',
    19. component: () => import('../pages/RegisterPage.vue'),
    20. meta: { requiresAuth: false } },
    21. { path: '/account/dashboard', name: 'Dashboard',
    22. component: () => import('../pages/DashboardPage.vue'),
    23. meta: { requiresAuth: true } },
    24. { path: '/account/orders', name: 'Orders',
    25. component: () => import('../pages/OrdersPage.vue'),
    26. meta: { requiresAuth: true } },
    27. { path: '/account/wallet', name: 'Wallet',
    28. component: () => import('../pages/WalletPage.vue'),
    29. meta: { requiresAuth: true } },
    30. { path: '/account/settings', name: 'Settings',
    31. component: () => import('../pages/SettingsPage.vue'),
    32. meta: { requiresAuth: true } },
    33. ];

    Vue Router matches routes in the order they are defined. /checkout/success/:orderId has two segments, while /checkout/:id has only one, so they do not conflict. However, if someone visits /checkout/success, it will match the checkout route and treat success as a product ID. The checkout page must handle unknown IDs as PRODUCT_NOT_FOUND rather than rendering a blank screen.

    A minimal route guard implementation:

    1. // src/router/index.js
    2. import { createRouter, createWebHistory } from 'vue-router';
    3. import { routes } from './routes.js';
    4. import { useAuthStore } from '../stores/auth.js';
    5. const router = createRouter({ history: createWebHistory(), routes });
    6. router.beforeEach((to) => {
    7. const auth = useAuthStore();
    8. if (to.meta.requiresAuth && !auth.isLoggedIn) {
    9. return { name: 'Login', query: { redirect: to.fullPath } };
    10. }
    11. if ((to.name === 'Login' || to.name === 'Register') && auth.isLoggedIn) {
    12. return { name: 'Dashboard' };
    13. }
    14. return true;
    15. });
    16. export default router;

    After a successful login, the page reads the redirect parameter and navigates accordingly. This parameter must be an in-site path — that is, it must start with a single / and not with //. Otherwise, an attacker could craft a redirect link to take users to an external website.

    1. const target = typeof route.query.redirect === 'string' && /^\/(?!\/)/.test(route.query.redirect)
    2. ? route.query.redirect
    3. : '/account/dashboard';
    4. router.push(target);

    Route guards only improve front-end experience. In a real project, the login token should be stored in an httpOnly Cookie, not in localStorage. Every account-related API must also be authenticated on the server side.

    3. Visual Consistency: Design Tokens First

    When each page is generated independently, they tend to use different colors and spacing values, leading to a fragmented overall design. The solution is to define design tokens first: centralize colors, font sizes, spacing, and border radii into variables, and let pages only reference these variables.

    1. /* src/styles/tokens.css */
    2. :root {
    3. --color-primary: #0958d9;
    4. --color-primary-hover: #003eb3;
    5. --color-text: #1f2329;
    6. --color-text-secondary: #646a73;
    7. --color-bg: #f5f6f7;
    8. --color-danger: #d93025;
    9. --font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
    10. --font-size-sm: 14px;
    11. --font-size-base: 16px;
    12. --font-size-lg: 20px;
    13. --font-size-xl: 24px;
    14. --font-weight-normal: 400;
    15. --font-weight-bold: 600;
    16. --line-height-base: 1.6;
    17. --space-1: 4px;
    18. --space-2: 8px;
    19. --space-4: 16px;
    20. --space-6: 24px;
    21. --radius: 6px;
    22. }
    23. body {
    24. font-family: var(--font-family);
    25. font-size: var(--font-size-base);
    26. line-height: var(--line-height-base);
    27. color: var(--color-text);
    28. background: var(--color-bg);
    29. }
    30. h1 {
    31. font-size: var(--font-size-xl);
    32. font-weight: var(--font-weight-bold);
    33. }
    34. .btn-primary {
    35. background: var(--color-primary);
    36. color: #ffffff;
    37. font-size: var(--font-size-base);
    38. padding: var(--space-2) var(--space-4);
    39. border-radius: var(--radius);
    40. }
    41. .btn-primary:hover:not(:disabled) {
    42. background: var(--color-primary-hover);
    43. }
    44. .btn-primary:disabled {
    45. opacity: 0.5;
    46. cursor: not-allowed;
    47. }

    Button color contrast needs to be calculated separately. Using the WCAG 2.x relative luminance formula, white text on #1677ff has a contrast ratio of approximately 4.1:1, which is below the 4.5:1 threshold required for normal text. Changing the primary color to #0958d9 brings the contrast ratio to approximately 6.2:1, which passes. The hover color should be darker than the primary color. If it becomes lighter on hover, the contrast ratio for white text will decrease further.

    The verification method is to check the text and background color pairs for primary buttons, labels, and links using a color picker or a tool like the WebAIM Contrast Checker, and record the results.

    Inconsistent product image heights are another common issue. If pages hardcode image URLs or leave them blank, card heights will vary. A recommended approach is to create a reusable image component with a fixed aspect ratio and a unified placeholder for load failures.

    1. <!-- src/components/ProductImage.vue -->
    2. <template>
    3. <div class="product-image">
    4. <img v-if="src && !failed" :src="src" :alt="alt" @error="failed = true" />
    5. <span v-else class="product-image__placeholder">No image available</span>
    6. </div>
    7. </template>
    8. <script setup>
    9. import { ref } from 'vue';
    10. defineProps({
    11. src: { type: String, default: '' },
    12. alt: { type: String, default: '' },
    13. });
    14. const failed = ref(false);
    15. </script>
    1. .product-image {
    2. width: 100%;
    3. aspect-ratio: 4 / 3;
    4. background: var(--color-bg);
    5. border-radius: var(--radius);
    6. overflow: hidden;
    7. }
    8. .product-image img {
    9. width: 100%;
    10. height: 100%;
    11. object-fit: cover;
    12. }
    13. .auth-form {
    14. width: 100%;
    15. max-width: 400px;
    16. margin: 0 auto;
    17. }
    18. @media (max-width: 767px) {
    19. .product-grid {
    20. grid-template-columns: repeat(2, 1fr);
    21. }
    22. }

    Forms such as login and registration should not use fixed widths. Fixed widths will overflow on narrow screens. We recommend using a combination of max-width and percentage widths, and adjusting the grid column count at breakpoints.

    4. Decoupling the Data Layer from Views

    Embedding mock data directly into page components is a frequent issue in generated code. When it comes time to integrate real APIs, almost every page will need to be modified. The correct approach is to centralize data fetching in a service layer, so pages only call service functions.

    1. // src/mock/products.js
    2. export const products = [
    3. { id: 'p-1001', name: 'Sample Product A', price: 199, stock: 20, image: '' },
    4. { id: 'p-1002', name: 'Sample Product B', price: 89, stock: 0, image: '' },
    5. ];

    The service layer throws exceptions with error codes, and pages display messages based on those codes. Error codes are defined centrally in a single class:

    1. // src/utils/errors.js
    2. export class AppError extends Error {
    3. constructor(code) {
    4. super(code);
    5. this.name = 'AppError';
    6. this.code = code;
    7. }
    8. }
    1. // src/services/productService.js
    2. import { products } from '../mock/products.js';
    3. import { AppError } from '../utils/errors.js';
    4. const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
    5. export async function listProducts() {
    6. await delay(200);
    7. return products.map((item) => ({ ...item }));
    8. }
    9. export async function getProduct(id) {
    10. await delay(200);
    11. const item = products.find((p) => p.id === id);
    12. if (!item) throw new AppError('PRODUCT_NOT_FOUND');
    13. return { ...item };
    14. }

    The service layer uses the spread operator to return copies of objects. This ensures that when pages modify data, the mock source data is not polluted.

    The mapping from error codes to human-readable messages is kept in a separate file:

    1. // src/utils/errorMessages.js
    2. import { AppError } from './errors.js';
    3. const messages = {
    4. PRODUCT_NOT_FOUND: 'Product not found or no longer available',
    5. OUT_OF_STOCK: 'Insufficient stock, please adjust the quantity',
    6. NETWORK_ERROR: 'A network issue occurred, please retry later',
    7. };
    8. export function toMessage(error) {
    9. if (error instanceof AppError && messages[error.code]) {
    10. return messages[error.code];
    11. }
    12. return 'Operation failed, please retry later';
    13. }

    The zero-stock rule must be enforced on two pages simultaneously. The product detail page disables the purchase button and displays “Out of stock.” The checkout page re-checks the quantity before submission and returns OUT_OF_STOCK when the quantity exceeds available stock.

    1. // Product detail page script snippet
    2. const product = ref(null);
    3. const loadError = ref('');
    4. const soldOut = ref(true);
    5. async function loadProduct() {
    6. try {
    7. product.value = await getProduct(route.params.id);
    8. soldOut.value = product.value.stock <= 0;
    9. } catch (error) {
    10. loadError.value = toMessage(error);
    11. }
    12. }

    5. Acceptance Checklist for AI-Generated Code

    Before deploying AI-generated frontend code, run through the following checklist:

    Routing and navigation:

    • Access all ten routes one by one; verify that each page loads without errors.
    • Test the transaction flow: product detail → checkout → checkout success. Confirm the order ID appears on the success page.
    • Log out and try to access a protected route; confirm you are redirected to the login page with the correct redirect parameter.

    Visual consistency:

    • Use the browser’s color picker to verify that no page has hardcoded color values outside the design tokens.
    • Check button states (normal, hover, disabled) on at least two different pages and compare them.
    • Resize the viewport to 375px and 1440px, and take screenshots of the home page and product detail page.

    Data and errors:

    • Enter a non-existent product ID (e.g., /products/p-9999) and confirm the page displays the PRODUCT_NOT_FOUND message without crashing.
    • Add more items to the cart than the available stock limit, and confirm the checkout page returns OUT_OF_STOCK.
    • Verify that no page component imports mock data directly; all data access goes through the service layer.

    Build and startup:

    • Run npm install and npm run dev on a clean machine to confirm a one-shot startup.
    • Run npm run build and confirm no errors in the build output.
    • Check the browser console for any warnings or errors after the first screen loads.

    Conclusion

    Building an e-commerce frontend with AI programming tools requires more than just generating individual pages. The key is to establish clear contracts — for routes, parameters, design tokens, and error handling — before code generation begins. These contracts ensure that pages work together as a cohesive system, are visually consistent, and remain maintainable when real APIs are integrated. By adhering to the five acceptance dimensions and running the checklist above, you can reliably evaluate and improve AI-generated frontend code.