Edge Computing × Frontend: Make Your Site Blazing Fast with Cloudflare Workers/Vercel Edge

前端工程(Updated Jun 2, 2026)

Why Does Frontend Need Edge Computing?

In traditional architectures, user requests must traverse half the internet to reach origin servers:

User (Tokyo) → CDN Node (Tokyo, static cache only) → Origin (US West, dynamic computation)
Latency: ~10ms          ~150ms cross-Pacific                ~50ms compute
Total: ~210ms

Edge computing pushes computation logic to the node closest to the user:

User (Tokyo) → Edge Node (Tokyo, direct compute)
Latency: ~10ms        ~5ms local compute
Total: ~15ms

14x latency reduction — that's the power of edge computing.


Comparing the Three Major Edge Platforms

Dimension Cloudflare Workers Vercel Edge Functions Deno Deploy
Runtime V8 Isolate V8 Isolate Deno
Cold Start <5ms <5ms ~20ms
Global Nodes 300+ cities 30+ regions 35+ regions
Free Tier 100K req/day Per-project billing 1M req/month
Languages JS/TS/WASM JS/TS JS/TS/WASM
Bundle Size Limit 10MB 4MB Unlimited
KV Storage Workers KV Edge Config Deno KV
Framework Integration Framework-agnostic Deep Next.js integration Fresh

Practical Scenario 1: Geo Routing

Route users to different content based on geographic location with zero latency:

// Cloudflare Workers
export default {
  async fetch(request: Request, env: Env, ctx: ExecutionContext) {
    const country = request.cf?.country as string;

    const routes: Record<string, string> = {
      CN: 'https://cn.example.com',
      JP: 'https://jp.example.com',
      US: 'https://us.example.com',
      EU: 'https://eu.example.com',
    };

    const target = routes[country] || routes['US'];

    return Response.redirect(target, 302);
  },
};

Vercel Edge Version

// middleware.ts (Next.js)
import { NextRequest, NextResponse } from 'next/server';

export function middleware(request: NextRequest) {
  const country = request.geo?.country || 'US';

  const localeMap: Record<string, string> = {
    CN: '/zh-CN',
    TW: '/zh-TW',
    JP: '/ja',
  };

  const locale = localeMap[country] || '/en';

  if (!request.nextUrl.pathname.startsWith(locale)) {
    return NextResponse.redirect(new URL(locale, request.url));
  }

  return NextResponse.next();
}

export const config = {
  matcher: ['/((?!api|_next/static).*)'],
};

Practical Scenario 2: A/B Testing

Route traffic at the edge layer — no client-side JavaScript needed:

export default {
  async fetch(request: Request, env: Env) {
    const url = new URL(request.url);

    // Read or assign experiment group
    let variant = getCookie(request, 'ab-variant');

    if (!variant) {
      variant = Math.random() < 0.5 ? 'control' : 'experiment';
    }

    // Read corresponding version HTML from KV
    const html = await env.KV.get(`landing:${variant}`);

    const response = new Response(html, {
      headers: { 'Content-Type': 'text/html' },
    });

    // Set cookie to maintain group consistency
    response.headers.append(
      'Set-Cookie',
      `ab-variant=${variant}; Path=/; Max-Age=86400`
    );

    return response;
  },
};

function getCookie(request: Request, name: string): string | null {
  const cookies = request.headers.get('Cookie') || '';
  const match = cookies.match(new RegExp(`${name}=([^;]+)`));
  return match ? match[1] : null;
}

Advantages Comparison

Approach FOUC Performance Impact SEO Friendly Complexity
Client-side JS routing ❌ Flickers Lowers LCP Low
Server-side routing ✅ No flicker Increases latency Medium
Edge routing ✅ No flicker Nearly no impact Medium

Practical Scenario 3: Personalized Content

export default {
  async fetch(request: Request, env: Env) {
    const country = request.cf?.country;
    const timezone = request.cf?.timezone;

    // Display local time based on timezone
    const localTime = new Date().toLocaleTimeString('en-US', {
      timeZone: timezone,
    });

    // Display local currency based on country
    const currencyMap: Record<string, { symbol: string; rate: number }> = {
      CN: { symbol: '¥', rate: 7.2 },
      JP: { symbol: '¥', rate: 150 },
      US: { symbol: '$', rate: 1 },
    };

    const currency = currencyMap[country] || currencyMap['US'];

    // Fetch base page and inject personalized data
    const response = await fetch(request);
    const html = await response.text();

    const personalized = html
      .replace('{{LOCAL_TIME}}', localTime)
      .replace('{{CURRENCY_SYMBOL}}', currency.symbol);

    return new Response(personalized, {
      headers: response.headers,
    });
  },
};

Practical Scenario 4: API Aggregation and Caching

Aggregate multiple APIs at the edge layer to reduce client requests:

export default {
  async fetch(request: Request, env: Env, ctx: ExecutionContext) {
    const cache = caches.default;
    const cacheKey = new Request(request.url);

    // 1. Check edge cache
    let response = await cache.match(cacheKey);
    if (response) return response;

    // 2. Parallel requests to multiple APIs
    const [user, posts, notifications] = await Promise.all([
      fetch('https://api.example.com/user', { headers: request.headers }),
      fetch('https://api.example.com/posts?limit=10'),
      fetch('https://api.example.com/notifications/unread'),
    ]);

    // 3. Aggregate responses
    const data = {
      user: await user.json(),
      posts: await posts.json(),
      notifications: await notifications.json(),
    };

    response = new Response(JSON.stringify(data), {
      headers: {
        'Content-Type': 'application/json',
        'Cache-Control': 'public, max-age=60',
      },
    });

    // 4. Write to edge cache
    ctx.waitUntil(cache.put(cacheKey, response.clone()));

    return response;
  },
};

Edge KV Storage: Global Low-Latency Database

Cloudflare Workers KV

// Write
await env.KV.put('user:123:preferences', JSON.stringify({
  theme: 'dark',
  language: 'zh-CN',
}));

// Read (eventually consistent, ~60s global sync)
const prefs = await env.KV.get('user:123:preferences', 'json');

// List
const list = await env.KV.list({ prefix: 'user:123:' });

Vercel Edge Config

import { get } from '@vercel/edge-config';

// Read configuration (globally synced, ~1s latency)
const flags = await get('feature-flags');

if (flags?.newHomepage) {
  return newHomepage();
}
return oldHomepage();

Migrating from Traditional Architectures

Migration Path

Phase 1: Static assets on CDN (1-2 days)
  → HTML/JS/CSS/images → CDN edge cache
  → Dynamic requests still go to origin

Phase 2: Edge middleware (1-2 weeks)
  → Redirects, A/B testing, Geo routing → Edge
  → Business logic still on origin

Phase 3: Lightweight API edge-ification (2-4 weeks)
  → Read-heavy APIs → Edge + KV
  → Write operations still go to origin

Phase 4: Heavy logic edge-ification (on demand)
  → SSR → Edge SSR
  → Streaming responses → Edge Streaming

Considerations

Limitation Description Mitigation
No Node.js APIs No fs, path, etc. Use Web APIs instead
Execution time limit Workers: 30ms (free) / 30s (paid) Split long tasks
Bundle size limit Workers: 10MB Tree-shaking, WASM
No global state Isolated isolate per request Persist with KV/D1
Cold start non-zero V8 Isolate ~5ms Warm key routes

Performance Benchmarks

The ToolsKu site uses Cloudflare CDN + static export architecture:

Metric              Traditional SSR    Edge Static
TTFB                200-500ms          10-30ms
LCP                 1.5-3s             0.3-0.8s
Global P50 Latency  150ms              15ms
Global P99 Latency  800ms              50ms

Summary

Edge computing is the ultimate weapon for frontend performance optimization — it's not about saving 50ms on the server, but about reducing 150ms of network latency to 5ms. In 2026, if your dynamic pages aren't running on the edge yet, you're wasting 100ms+ of your users' waiting time. From Geo routing and A/B testing to API aggregation, edge computing gives frontend developers the superpower to "deploy code in 300+ cities worldwide."

Try these browser-local tools — no sign-up required →

#边缘计算#CDN#Edge Functions#性能优化#Cloudflare Workers