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 |
// src/router/routes.jsexport const routes = [{ path: '/', name: 'ProductList',component: () => import('../pages/ProductListPage.vue'),meta: { requiresAuth: false } },{ path: '/products/:id', name: 'ProductDetail',component: () => import('../pages/ProductDetailPage.vue'),meta: { requiresAuth: false } },{ path: '/checkout/success/:orderId', name: 'CheckoutSuccess',component: () => import('../pages/CheckoutSuccessPage.vue'),meta: { requiresAuth: true } },{ path: '/checkout/:id', name: 'Checkout',component: () => import('../pages/CheckoutPage.vue'),meta: { requiresAuth: true } },{ path: '/login', name: 'Login',component: () => import('../pages/LoginPage.vue'),meta: { requiresAuth: false } },{ path: '/register', name: 'Register',component: () => import('../pages/RegisterPage.vue'),meta: { requiresAuth: false } },{ path: '/account/dashboard', name: 'Dashboard',component: () => import('../pages/DashboardPage.vue'),meta: { requiresAuth: true } },{ path: '/account/orders', name: 'Orders',component: () => import('../pages/OrdersPage.vue'),meta: { requiresAuth: true } },{ path: '/account/wallet', name: 'Wallet',component: () => import('../pages/WalletPage.vue'),meta: { requiresAuth: true } },{ path: '/account/settings', name: 'Settings',component: () => import('../pages/SettingsPage.vue'),meta: { requiresAuth: true } },];
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:
// src/router/index.jsimport { createRouter, createWebHistory } from 'vue-router';import { routes } from './routes.js';import { useAuthStore } from '../stores/auth.js';const router = createRouter({ history: createWebHistory(), routes });router.beforeEach((to) => {const auth = useAuthStore();if (to.meta.requiresAuth && !auth.isLoggedIn) {return { name: 'Login', query: { redirect: to.fullPath } };}if ((to.name === 'Login' || to.name === 'Register') && auth.isLoggedIn) {return { name: 'Dashboard' };}return true;});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.
const target = typeof route.query.redirect === 'string' && /^\/(?!\/)/.test(route.query.redirect)? route.query.redirect: '/account/dashboard';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.
/* src/styles/tokens.css */:root {--color-primary: #0958d9;--color-primary-hover: #003eb3;--color-text: #1f2329;--color-text-secondary: #646a73;--color-bg: #f5f6f7;--color-danger: #d93025;--font-family: "PingFang SC", "Microsoft YaHei", sans-serif;--font-size-sm: 14px;--font-size-base: 16px;--font-size-lg: 20px;--font-size-xl: 24px;--font-weight-normal: 400;--font-weight-bold: 600;--line-height-base: 1.6;--space-1: 4px;--space-2: 8px;--space-4: 16px;--space-6: 24px;--radius: 6px;}body {font-family: var(--font-family);font-size: var(--font-size-base);line-height: var(--line-height-base);color: var(--color-text);background: var(--color-bg);}h1 {font-size: var(--font-size-xl);font-weight: var(--font-weight-bold);}.btn-primary {background: var(--color-primary);color: #ffffff;font-size: var(--font-size-base);padding: var(--space-2) var(--space-4);border-radius: var(--radius);}.btn-primary:hover:not(:disabled) {background: var(--color-primary-hover);}.btn-primary:disabled {opacity: 0.5;cursor: not-allowed;}
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.
<!-- src/components/ProductImage.vue --><template><div class="product-image"><img v-if="src && !failed" :src="src" :alt="alt" @error="failed = true" /><span v-else class="product-image__placeholder">No image available</span></div></template><script setup>import { ref } from 'vue';defineProps({src: { type: String, default: '' },alt: { type: String, default: '' },});const failed = ref(false);</script>
.product-image {width: 100%;aspect-ratio: 4 / 3;background: var(--color-bg);border-radius: var(--radius);overflow: hidden;}.product-image img {width: 100%;height: 100%;object-fit: cover;}.auth-form {width: 100%;max-width: 400px;margin: 0 auto;}@media (max-width: 767px) {.product-grid {grid-template-columns: repeat(2, 1fr);}}
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.
// src/mock/products.jsexport const products = [{ id: 'p-1001', name: 'Sample Product A', price: 199, stock: 20, image: '' },{ id: 'p-1002', name: 'Sample Product B', price: 89, stock: 0, image: '' },];
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:
// src/utils/errors.jsexport class AppError extends Error {constructor(code) {super(code);this.name = 'AppError';this.code = code;}}
// src/services/productService.jsimport { products } from '../mock/products.js';import { AppError } from '../utils/errors.js';const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));export async function listProducts() {await delay(200);return products.map((item) => ({ ...item }));}export async function getProduct(id) {await delay(200);const item = products.find((p) => p.id === id);if (!item) throw new AppError('PRODUCT_NOT_FOUND');return { ...item };}
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:
// src/utils/errorMessages.jsimport { AppError } from './errors.js';const messages = {PRODUCT_NOT_FOUND: 'Product not found or no longer available',OUT_OF_STOCK: 'Insufficient stock, please adjust the quantity',NETWORK_ERROR: 'A network issue occurred, please retry later',};export function toMessage(error) {if (error instanceof AppError && messages[error.code]) {return messages[error.code];}return 'Operation failed, please retry later';}
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.
// Product detail page script snippetconst product = ref(null);const loadError = ref('');const soldOut = ref(true);async function loadProduct() {try {product.value = await getProduct(route.params.id);soldOut.value = product.value.stock <= 0;} catch (error) {loadError.value = toMessage(error);}}
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
redirectparameter.
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 installandnpm run devon a clean machine to confirm a one-shot startup. - Run
npm run buildand 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.
