skills/infrastructure-performance/edge-commerce/SKILL.md
Reduce latency globally by running geo-routing, A/B tests, and personalization logic at the network edge using Cloudflare Workers or Vercel
npx skillsauth add finsilabs/awesome-ecommerce-skills edge-commerceInstall this skill globally with one command. Works with Claude Code, Cursor, and Windsurf.
3 of 9 scanners reported clean
Some scanners were skipped, did not run, or reported a non-clean status. Review each row below.
Edge computing executes code in the CDN PoP closest to each user, reducing latency from hundreds of milliseconds (round-trip to a central origin) to under 50ms. For e-commerce, this enables geo-routing (redirect UK users to a UK storefront), edge-side personalization (inject user tier into cached pages), instant A/B testing without origin round-trips, and distributed inventory caching via edge KV stores.
| Platform | Edge Capabilities | How to Use Them | |----------|-----------------|----------------| | Shopify | Shopify's CDN (Fastly) already serves stores from global edge locations | Use Shopify Markets for geo-routing and multi-currency without custom edge code; Markets handles currency, language, and domain routing natively | | WooCommerce | Add Cloudflare as your CDN/proxy to get edge capabilities | Cloudflare Workers (free tier: 100k requests/day) adds edge logic; configure in Cloudflare dashboard after adding your domain | | BigCommerce | BigCommerce uses Fastly CDN globally | Use BigCommerce's built-in multi-storefront feature for geo-routing; for custom edge logic add Cloudflare in front | | Custom / Headless | Full control — choose Cloudflare Workers, Vercel Edge Middleware, or Fastly Compute | Build custom geo-routing, A/B testing, and personalization at the edge; see implementation below |
uk.yourstore.com routes UK visitors automatically// Cloudflare Worker — deploy via Cloudflare dashboard
export default {
async fetch(request) {
const country = request.headers.get('CF-IPCountry') ?? 'US';
const url = new URL(request.url);
// Redirect UK users to UK store variant
if (country === 'GB' && !url.pathname.startsWith('/uk')) {
return Response.redirect(`https://${url.hostname}/uk${url.pathname}`, 302);
}
return fetch(request);
}
};
*yourstore.com/*Vercel Edge Middleware (Next.js) for geo-routing:
// middleware.ts — runs at the edge globally, <5ms
import { NextRequest, NextResponse } from 'next/server';
import { geolocation } from '@vercel/functions';
const REGION_MAP: Record<string, string> = {
GB: 'uk', DE: 'de', FR: 'fr', CA: 'ca', AU: 'au',
};
export function middleware(request: NextRequest) {
const { country } = geolocation(request);
const region = country ? REGION_MAP[country] : null;
// Redirect root to regional store
if (region && request.nextUrl.pathname === '/') {
const url = request.nextUrl.clone();
url.pathname = `/${region}`;
return NextResponse.redirect(url, { status: 302 });
}
// Pass country to origin for catalog/pricing logic
const response = NextResponse.next();
if (country) response.headers.set('x-user-country', country);
return response;
}
export const config = { matcher: ['/', '/products/:path*', '/collections/:path*'] };
Edge A/B testing (assign variant once, persist in cookie):
// In middleware.ts — no origin round-trip needed
const EXPERIMENTS = [
{ id: 'checkout-cta', buckets: [{ name: 'control', weight: 0.5 }, { name: 'variant-a', weight: 0.5 }] },
];
function assignVariant(buckets: Array<{name: string; weight: number}>) {
let r = Math.random(), cumulative = 0;
for (const b of buckets) {
cumulative += b.weight;
if (r < cumulative) return b.name;
}
return buckets[0].name;
}
// Add to existing middleware function:
for (const exp of EXPERIMENTS) {
const cookieName = `ab_${exp.id}`;
let variant = request.cookies.get(cookieName)?.value;
if (!variant) {
variant = assignVariant(exp.buckets);
response.cookies.set(cookieName, variant, { maxAge: 30 * 24 * 3600, httpOnly: true });
}
response.headers.set(`x-ab-${exp.id}`, variant); // available in your app for rendering
}
Cloudflare Workers KV for edge inventory caching:
// cloudflare-worker.ts — inventory cached at every Cloudflare PoP globally
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const url = new URL(request.url);
if (url.pathname.startsWith('/api/inventory/')) {
const productId = url.pathname.replace('/api/inventory/', '');
const cached = await env.INVENTORY_KV.get(productId, 'json');
if (cached) {
return new Response(JSON.stringify(cached), {
headers: { 'Content-Type': 'application/json', 'X-Edge-Cache': 'HIT' },
});
}
// Cache miss — fetch from origin and store for 60 seconds
const data = await fetch(`${env.ORIGIN_URL}/api/inventory/${productId}`).then(r => r.json());
await env.INVENTORY_KV.put(productId, JSON.stringify(data), { expirationTtl: 60 });
return new Response(JSON.stringify(data), {
headers: { 'Content-Type': 'application/json', 'X-Edge-Cache': 'MISS' },
});
}
return fetch(request);
},
};
KV namespace wrangler.toml:
name = "commerce-edge"
main = "src/index.ts"
compatibility_date = "2025-01-01"
[[kv_namespaces]]
binding = "INVENTORY_KV"
id = "your-kv-namespace-id"
Vercel Edge Config for instant feature flags:
// Read feature flags at edge — ~0ms latency (stored in PoP)
import { get } from '@vercel/edge-config';
export async function middleware(request: NextRequest) {
const maintenanceMode = await get<boolean>('maintenance_mode');
if (maintenanceMode) {
return NextResponse.rewrite(new URL('/maintenance', request.url));
}
return NextResponse.next();
}
Regardless of platform, measure these metrics:
| Problem | Solution |
|---------|----------|
| Edge making external API calls on every request | Cache external data in Edge Config or Workers KV; never make synchronous third-party API calls from edge middleware on the critical path |
| Personalized responses cached without Vary header | Set Vary: Cookie or a custom header that differentiates personalized responses; without it, one user's content can be served to others |
| Workers KV stale inventory causing oversells | Use edge KV only for displaying inventory status; always validate against the authoritative inventory source at checkout time |
| A/B variant flickering on first load | Set the variant cookie in the response before the page renders; on first visit, set the cookie and redirect to ensure consistent rendering |
tools
Let shoppers save products to a wishlist, share it with friends, and get notified when saved items come back in stock or drop in price
development
Build a themeable storefront with design tokens and CSS custom properties that supports white-labeling, multi-brand variants, and dark mode
development
Speed up product discovery with instant search suggestions, fuzzy typo matching, and category-aware results powered by Algolia or Elasticsearch
development
Build a mobile-first storefront with thumb-friendly navigation, sticky add-to-cart buttons, and touch-optimized components for high mobile conversion