Last year, I led the team that rebuilt the member area of a subscription e-commerce app. The new experience gave members a cart that follows them across every screen, and it replaced the frontend underneath.
My first frontend commit landed on July 22, 2025. The release candidate merged in early December 2025: 209 files, 21,206 lines added and 3,248 removed. Over the next six months, we deleted about the same amount of legacy code.
The part I'm proudest of isn't a component. It's a handful of architecture calls I made in the first ten weeks, before most of the features existed. They're what let a small team build in parallel and ship on the date. For each one, I'll cover the problem, why we chose what we did, and how it has held up since launch.
Where We Started
The app is Laravel with a Vue 2 frontend. The old member area used an island architecture: each Blade page mounted its own Vue app, from one of about 55 Vite entry points. Plan and order history shared one app. Specials, gifts and deactivation each had their own. Every navigation was a full page load, so Vue booted again, the user was fetched again, and any state was lost.
That worked while the pages were independent. The new experience made them depend on each other. The cart had to follow the member onto every screen. The same product card had to work on the home page, in the market, in the cart and in the plan editor. And money, promotions and order minimums had to be right everywhere at once.
One App, Not Islands
The first call was the shape of the app. We needed shared state across the whole member area, on a fixed date, so I chose one Vue 2 single-page app for everything behind login, served by Laravel.
The obvious alternative was Nuxt and Vue 3, which we already used on parts of the marketing site. But nothing behind login needs to be found by search engines, so server rendering wouldn't buy us anything there. The team knew Vue 2, and our design system was built on it. Laravel kept handling authentication, middleware and named routes, and every member route returns the same view:
Route::view('/home', 'app.index')->name('app.home');
Route::view('/cart', 'app.index')->name('app.cart');
Route::view('/market/{any?}', 'app.index')->name('app.market');
Route::view('/plan', 'app.index')->name('app.membership');
Staying on Vue 2 meant taking on known debt, and we wrote it down on day one. The upgrade is now its own project: the design system needs to run Vue 2 and Vue 3 side by side, with a hard limit on how long it supports both. Because we planned for it, it isn't a surprise to anyone.
We shipped on the date, and I'd make the same call again.
Seams Before Features
We had a small team, about five months, and a backend team rebuilding carts and products behind a new API at the same time. The tempting move was to start everyone on features right away. Instead, I spent the first weeks building the seams the rest of the team would work inside, while the others ramped up on the new backend and the designs. From late July to mid-October, most of my commits were:
- The app shell and layouts.
- The data layer.
- The stores and the boot sequence.
- The URL contract for modals.
- A folder per product area, with one controller component per route.
Checkout was the first real tenant. It was small enough to prove each seam before anyone else depended on it, and early enough that changing a seam was still quick.
Once the seams were in place, each product epic got its own folder: Plan and Membership, Market, Cart and Box Swapper, Orders, Checkout and Settings. One engineer owned each one. Controllers fetch data and coordinate, and the components below them take props and emit events.
app/
├── App.vue
├── router/
├── store/ thin, one module per server resource
├── models/ pure normalizers
├── services/ resource registry
├── components/ shared, presentational
└── domains/
├── cart/ controllers/ components/
├── checkout/
├── home/
├── market/ controllers/ pages/ router.js
├── membership/
├── edit-plan/
└── settings/
There was less to demo in those first weeks, but it paid off as soon as the features started. The domains were built in parallel with few collisions, because each one had its own folder, its own controller and the same building blocks. Conway's law shows up whether you plan for it or not. This time we planned for it.
The Server Owns the Money
The cart is where the business rules live:
- Prices, promotions and credits.
- Substitutions.
- An order minimum (a number of packs or a dollar amount).
- Which items a member can skip, and which quantities are locked.
The old dashboard calculated parts of this in the browser. Its order summary added tax, subtracted promotions and summed specials, and its box builders multiplied base prices by quantities. Every pricing change had to land in two places, and the two didn't always agree.
A rich client store with optimistic updates would have felt instant, but it would have kept the rules in two places. For anything involving money, I wanted one source of truth. So the cart store is thin. It holds the server's response and a status, nothing else:
async fetchCart({ commit, rootGetters }) {
commit('SET_STATUS', OPERATION_STATUS.PENDING);
const response = await carts.getOne(rootGetters['user/cartId'], {
include: ['cartItems.offer', 'cartItems.product.images', 'promotion.promoItems.product'],
});
commit('SET_CART', { ...response.data, meta: response.meta });
commit('SET_STATUS', OPERATION_STATUS.RESOLVED);
},
Totals come from the server's meta. The client only renames keys and fills in defaults:
export const buildCartSummary = (cart) => {
if (!cart?.meta) return { totals: {}, formatted: {} };
return {
totals: { ...cartSummaryTotalsTemplate, ...objectKeysToCamel(cart.meta.totals) },
formatted: { ...cartSummaryFormattedTemplate, ...objectKeysToCamel(cart.meta.totalsFormatted) },
};
};
The order minimum comes from a config endpoint, not a constant in the bundle, and the per-item rules come from the server too. For each item, the cart response says whether the member can skip it (canSkip), whether they can lower the quantity (canDecrement), and whether the action needs a confirmation. The UI renders those answers. It never works out for itself whether skipping a $180 box would drop the order below the minimum.
Every write goes through one wrapper that calls the server, refetches the cart, and logs failures with enough context to debug them:
async execAction(action, request, context = {}) {
try {
onBeforeAction.call(this, action, context);
const response = await withRefresh(request, ['cart/fetchCart']);
onAfterAction.call(this, action, response, context);
} catch (error) {
logError(error, { category: 'cart', action, context: { cart: context } });
onError.call(this, action, error, context);
throw error;
}
},
Every click is a round trip, so we made the waits clear instead of hiding them. Per-button pending states mean only the control you touched shows a spinner and disables. The server team took on more work too, because the cart response had to carry those per-item answers, not just the data.
This has held up well. Since launch, we've changed the pricing around the cart thresholds several times. Each change shipped as new values from the API, and none of them touched the app's logic. Optimistic UI is a great tool when being briefly wrong costs nothing, but a wrong total in a cart isn't free.
Normalize Once, Join Late
The new APIs speak JSON:API, so a product arrives wrapped in nested data envelopes:
product.variants.data[].currentOffer.datacartItems.data[].product.data.images.data
And it comes from three API versions with slightly different shapes. If components read that directly, every one of them has to know the shape of the API.
So responses are converted into plain objects once, when the data enters the app. I chose pure functions over model classes: each model file is a set of functions with JSDoc typedefs. They're easy to test, they serialize cleanly into Vuex, and they give editors type hints without adding TypeScript to a Vue 2 build:
/**
* @param {Object} product JSON:API product with currentOffer, images and variants included
* @returns {NormalizedProduct}
*/
export const normalizeProduct = (product) => {
const attrs = product.attributes || product;
const media = mapProductImages(product);
const offer = resolveCurrentOffer(product);
return {
id: product.id,
slug: attrs.slug ?? null,
name: attrs.name ?? null,
contentSize: attrs.contentSize ?? 0,
...offer,
satisfiesOrderMinimum: Boolean(attrs.satisfiesOrderMinimum),
isBox: [merchGroups.CURATED_BOX, merchGroups.LIMITED_TIME_BOX].includes(offer.merchGroup),
image: media.primary?.url ?? null,
media,
variants: (product.variants?.data || []).map(normalizeVariant),
};
};
The second half of this decision mattered more: keep the catalog and the cart separate, and join them when you read. The catalog changes slowly, so we cache it for minutes. The cart changes on every click. If "is this in my cart?" lived on the product, every add to cart would make the catalog cache stale.
Instead, the cart is indexed once by offer ID, and products are enriched when a list renders:
/**
* @param {NormalizedProduct[]} products
* @param {Map<string, NormalizedCartItem>} cartItemsByOfferId
* @returns {EnrichedProduct[]}
*/
export const enrichProductsWithCartStatus = (products, cartItemsByOfferId) =>
products.map((product) => {
const cartItem = cartItemsByOfferId.get(product.offerId);
const variantInCart =
product.variants.find((variant) => cartItemsByOfferId.has(variant.offerId))?.offerId ?? null;
return {
...product,
inCart: Boolean(cartItem || variantInCart),
isSkipped: cartItem?.isSkipped ?? false,
isIncreaseLocked: cartItem?.isIncreaseLocked ?? false,
quantity: cartItem?.quantity ?? 0,
variantInCart,
};
});
A renderless CartProvider at the root of the app builds that index. It watches the raw cart and sorts every item into buckets in a single pass: curated boxes, recurring items, one-time items, limited-time items and promotions. It exposes the results through provide, so every component that needs the cart injects the same derived view instead of filtering the raw response again.
normalizeAndCacheCart() {
const items = normalizeCartItemsFromCart(this.rawCart?.cartItems, this.rawCart?.meta?.cartItemActions);
const cartItemsByOfferId = new Map();
for (const item of items) {
bucketFor(item).push(item);
cartItemsByOfferId.set(item.offerId, item);
}
this.cartItemsByOfferId = cartItemsByOfferId;
this.summary = buildCartSummary(this.rawCart);
},
To keep the migration safe, the products store held both the raw response and the normalized version for a while. Today, 29 call sites read the normalized version and 4 still read the raw one, and finishing that is on my list.
It has held up very well. When curations and Popular Plans arrived after launch, they were new normalizers and a new bucket, not changes across dozens of components.
Load What's Visible First
The market's "All" tab shows several product groups: limited-time boxes, curated boxes, recurring items and specials. Each group is a separate request with heavy includes: offers, images, and variants with their own offers. The home page upsell, the cart recommendations and the plan editor need the same groups.
One big request would make the first paint wait for the largest payload. Fetching each tab only when it's opened would make every tab switch wait. Instead, the store waits only for the group the member is looking at, starts the rest in the background, and shares the results:
async fetchProducts({ dispatch, rootGetters }, { priorityMerchGroup = null } = {}) {
const locationId = rootGetters['user/locationId'];
if (priorityMerchGroup) {
await dispatch('fetchProductsForMerchGroup', { locationId, merchGroup: priorityMerchGroup });
}
Object.values(merchGroups)
.filter((group) => group !== priorityMerchGroup)
.forEach((merchGroup) => {
dispatch('fetchProductsForMerchGroup', { locationId, merchGroup }).catch((error) =>
logError(error, { category: 'products', action: 'warm', tags: { merchGroup } }),
);
});
},
Three rules keep the warming safe:
- Each group has its own status. A skeleton shows per section, not per page, and one failed group doesn't blank the others.
- Requests already in flight are reused. If the market, the cart upsell and the recommendations all ask for the same group at once, only the first request goes out.
- Results are cached for five minutes, with a
forceRefreshescape hatch.
async fetchProductsForMerchGroup({ commit, getters, state }, { merchGroup, forceRefresh = false }) {
if (state.products[merchGroup]?.status === OPERATION_STATUS.PENDING) {
return getters.productsByMerchGroup(merchGroup);
}
if (!forceRefresh && getters.isCached(merchGroup)) {
return getters.productsByMerchGroup(merchGroup);
}
// fetch, normalize once, commit with fetchedAt and a per-group status
},
The tabs are wrapped in keep-alive, so switching back to a tab doesn't rebuild a list you've already seen.
The catalog can be up to five minutes stale, and that's safe because of the previous decision: whether something is in your cart comes from the live cart, never the cached catalog. Today, the market, the home page upsell, the cart recommendations and the plan editor all read from the same store, so a group fetched for one screen is already there for the others.
Let the Route Decide
The same product card appears in four places, and "add" means something different in each:
- In the market and on the home page, add changes the next order immediately.
- In the plan editor, changes are a draft until the member saves.
- On some screens, the card is read-only.
A separate card for each context would mean four places to fix every bug, and a mode prop would have to pass through components that don't care about it. Instead, the route declares the mode, and components ask for it. There are three modes, declared in route metadata:
export const CART_MODES = Object.freeze({
SYNC: 'sync',
DRAFT: 'draft',
INFORMATIVE: 'informative',
});
{ path: '/app/market', meta: { cartExecutionMode: CART_MODES.SYNC } }
{ path: '/app/plan/customize', meta: { cartExecutionMode: CART_MODES.DRAFT } }
One resolver walks from the most specific matched route outward, and falls back to the safe default, read-only:
export default function resolveCartMode({ route }) {
for (let i = route.matched.length - 1; i >= 0; i--) {
const declared = route.matched[i]?.meta?.cartExecutionMode;
if (isCartMode(declared)) return { mode: declared };
}
return { mode: CART_MODES.INFORMATIVE };
}
Components pick their control from the mode, not from where they think they're mounted:
controlType() {
if (!this.isInCart) return 'add';
if (this.cartMode === CART_MODES.DRAFT) return 'dropdown';
if (this.isSkipped) return 'unskip';
return this.hasVariants ? 'dropdown' : 'add';
},
Draft mode has a small store of its own. When the cart loads, it snapshots the plan items, applies edits locally, and tracks whether anything has changed. A route guard asks before you leave with unsaved changes.
On save, the editor sends the whole plan in one call, not a replay of every click:
await withRefresh(
() => carts.action(cartId, 'save-recurring-items', {
cart: current.map(({ offerId, quantity }) => ({ offer: { id: offerId }, qty: quantity })),
}),
['cart/fetchCart'],
);
The server validates the complete plan against the minimums in one place, in one transaction, so there's no half-applied state if the fifth of seven changes fails.
Because the mode comes from the route, debugging means knowing which route you're on. I kept that manageable with a single resolver, a read-only default, and only three modes.
It paid off when Popular Plans shipped months later. It appears in both the market and the plan editor, and its product modal reuses the same cards and asks the same resolver which mode it's in. We didn't build a new card.
Resource Names, Not URLs
While we rebuilt the frontend, the backend team moved carts and products to a new e-commerce API. If components had known endpoint URLs, each project would have blocked the other.
So components only know resource names, and one config file maps each resource to an API version:
export default {
defaultVersion: 'v1',
versions: {
v1: { baseUrl: `${apiBase}/api/v1` },
v2: { baseUrl: `${apiBase}/api/ecom/v1` },
logistics: { baseUrl: `${apiBase}/api/logistics/v1` },
},
resourceVersions: {
carts: 'v2',
'cart-items': 'v2',
products: 'v2',
'shipment-timings': 'logistics',
},
};
export const carts = api.resource('carts');
When the backend moved a resource, the frontend change was one line. That's what let two teams work at the same time without waiting on each other.
What I'd Do Differently
- Give temporary bridges an end date. Checkout needed order data the new stores didn't provide yet, so we connected it to the old "unified" store. Startup then waited on two more sequential requests before anything rendered. It shipped and it worked, but it stayed for six months and quietly joined the critical path for every page. Next time, it gets a removal ticket and a date on the day it's built.
- Do the same for migration shapes. Keeping raw and normalized products side by side made the migration safe, but it needed an end date too.
- Make the cart mode visible. I'd add a small development overlay that shows the current mode, so "why does this card behave differently here?" is answered by looking at the screen instead of reading the router.
Deleting the Old Code Is Part of the Deliverable
The release candidate added about 21,000 lines. Over the next six months, we removed about 21,000:
- 7,006 lines of the old dashboard.
- 1,922 lines of the old specials pages.
- 12,267 lines of in-app Storybook and legacy components, which moved into the shared design system.
- The temporary bridge store.
A rewrite isn't finished when the new code ships. It's finished when the old code is gone. Put the deletion work on the roadmap next to the launch, or it won't happen.
The Principles
- Write down what each decision costs, next to the decision.
- Spend the first weeks on seams. The first engineer's job is to make parallel work possible.
- Let the server own money and rules. The client renders answers. It doesn't recalculate them.
- Normalize at the edge, join late. Cache what changes slowly, read what changes fast, and join them at render time.
- Load what's visible, warm the rest, with per-section status, shared in-flight requests and a short cache.
- Put behavior on the route, not in the component, with a safe default.
- Give every temporary bridge an expiry date, and schedule the deletion with the launch.
The features will keep changing. These decisions are what let us keep changing them quickly.