Edge Rendering
Master edge rendering — deploying server-side rendering to edge locations for minimal latency, understanding edge runtime constraints, regional deployment strategies, edge middleware patterns, data locality considerations, and platform-specific optimization for Cloudflare Workers, Vercel Edge, and Deno Deploy.
When to Use
- Users are geographically distributed and origin server latency varies by region
- TTFB is high for users far from the origin server (>200ms)
- Server-side rendering is needed but origin-only deployment adds latency
- Personalization (A/B tests, geo-targeting, localization) needs to happen before content delivery
- Authentication and authorization checks could run closer to the user
- API responses could be transformed or enriched at the edge
- Static generation is too stale but full origin SSR adds unnecessary latency
- Edge middleware is needed for redirects, rewrites, or header manipulation
- A global application needs consistent sub-100ms TTFB worldwide
- Feature flags need to be evaluated before page rendering without a client-side flash
Instructions
Understand edge versus origin architecture. Edge functions run in data centers close to the user (200+ locations) instead of a single origin:
Origin-only SSR:
User (Tokyo) → CDN → Origin (US-East) → DB → Render → Response
Network RTT: ~150ms | TTFB: ~350ms
Edge Rendering:
User (Tokyo) → Edge (Tokyo) → Render → Response
Network RTT: ~5ms | TTFB: ~50ms
Edge + Origin Data:
User (Tokyo) → Edge (Tokyo) → Origin API (US-East) → Edge Render → Response
Network RTT: ~5ms + ~150ms (data) | TTFB: ~200ms
(Still faster: user sees shell immediately via streaming)
Deploy edge functions on Cloudflare Workers. Workers run on V8 isolates with sub-millisecond cold starts:
// src/worker.ts — Cloudflare Worker
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const url = new URL(request.url);
// Edge-rendered HTML
const html = await renderPage(url.pathname, {
userCountry: request.cf?.country,
userCity: request.cf?.city,
});
return new Response(html, {
headers: {
'Content-Type': 'text/html; charset=utf-8',
'Cache-Control': 'public, max-age=60, s-maxage=300',
},
});
},
};
// wrangler.toml
// name = "my-app"
// main = "src/worker.ts"
// compatibility_date = "2024-01-01"
Use Vercel Edge Runtime for Next.js. Mark routes to run on the edge instead of Node.js:
// app/api/geo/route.ts — Edge API route
export const runtime = 'edge';
export async function GET(request: Request) {
const country = request.headers.get('x-vercel-ip-country') || 'US';
const city = request.headers.get('x-vercel-ip-city') || 'Unknown';
return Response.json({
country,
city,
timestamp: Date.now(),
});
}
// middleware.ts — geo-redirects and A/B tests at the edge
// Use request.geo?.country for geo-routing, cookies for A/B persistence
// Configure matcher to exclude static assets: /((?!_next/static|favicon).*)
Handle edge runtime constraints. Edge runtimes use a limited Web API subset (no Node.js APIs):
// Available at the edge:
// - fetch(), Request, Response, Headers
// - URL, URLSearchParams, URLPattern
// - crypto.subtle, crypto.getRandomValues
// - TextEncoder, TextDecoder
// - structuredClone, atob, btoa
// - setTimeout (limited), Promises, async/await
// - Web Streams API
// NOT available at the edge:
// - fs, path, child_process (no file system)
// - Buffer (use Uint8Array instead)
// - net, http (use fetch instead)
// - Most npm packages that use Node.js APIs
// Edge-compatible alternatives:
// Database: Neon serverless, PlanetScale, Turso (HTTP-based)
// KV Store: Cloudflare KV, Vercel KV, Upstash Redis
// ORM: Drizzle (with HTTP adapter), Prisma (with Accelerate)
Implement edge caching for dynamic content. Cache rendered pages at the edge with smart invalidation:
// Cloudflare Workers — Cache API
async function handleRequest(request: Request): Promise<Response> {
const cache = caches.default;
const cacheKey = new Request(request.url, request);
// Check edge cache
let response = await cache.match(cacheKey);
if (response) {
return response;
}
// Render at the edge
const html = await renderPage(request);
response = new Response(html, {
headers: {
'Content-Type': 'text/html',
'Cache-Control': 'public, s-maxage=300', // cache at edge for 5 min
},
});
// Store in edge cache (non-blocking)
const cacheResponse = response.clone();
await cache.put(cacheKey, cacheResponse);
return response;
}
Manage data locality. Edge rendering is fast only if data access is also fast. Strategies for reducing data latency:
// Strategy 1: Edge KV for read-heavy data
// Cloudflare KV: eventually consistent, <10ms reads globally
const config = await env.CONFIG_KV.get('site-config', 'json');
// Strategy 2: Edge-local database replicas
// Turso (libSQL): read replicas in 30+ regions
// Read from local replica, write to primary
import { createClient } from '@libsql/client';
const db = createClient({
url: 'libsql://db-name-region.turso.io',
authToken: '...',
});
// Strategy 3: Cache at the edge, fetch from origin
// Best for: data that changes infrequently, high read volume
const data = await env.CACHE.get(key, 'json');
if (!data) {
const fresh = await fetch('https://origin.example.com/api/data');
await env.CACHE.put(key, await fresh.text(), { expirationTtl: 300 });
}
// Strategy 4: Smart routing — render at the edge closest to the database
// Vercel: configure function regions to match database location
// export const preferredRegion = 'iad1'; // US East, near the DB
Monitor edge function performance. Instrument with Date.now() timing, log the edge location (request.cf?.colo on Cloudflare), and always fall back to fetch(request) on error. Track cold start frequency, P99 execution time, and cache hit rates via platform analytics (Cloudflare Analytics Engine, Vercel Analytics).
Details
Edge Runtime Cold Starts
Cloudflare Workers use V8 isolates with sub-millisecond cold starts; Vercel Edge Functions ~5ms. Both are far faster than Lambda (100-1000ms). Trade-off: no file system, no native modules, limited memory (128MB), and limited CPU time (10-50ms free tier). Design edge functions to be lightweight.
Worked Example: Cloudflare Blog
Runs entirely on Workers with streaming SSR. Blog posts render from Markdown in Workers KV, cached at the edge. First request renders and caches; subsequent requests serve in <5ms globally. Webhook-based cache purging on content updates. Result: <50ms TTFB worldwide, zero origin load for reads.
Worked Example: Shopify Oxygen
Deploys Remix storefronts to Cloudflare Workers. Edge rendering takes 20-50ms, Storefront API responds in 50-100ms, yielding 70-150ms total TTFB vs 200-400ms origin-only. Stale-while-revalidate caching drops frequently-accessed pages to <10ms TTFB.
Anti-Patterns
Edge rendering with origin-only databases. If every request queries a database in US-East, the edge latency advantage is negated. Use edge-local data stores (KV, replicas) or accept the benefit is limited to non-data-dependent content.
Heavy computation at the edge. Edge runtimes have strict CPU time limits (10-50ms on free tiers). Offload image processing and heavy transformations to origin functions. Use the edge for lightweight rendering, routing, and personalization.
Not falling back to origin on edge failure. Always implement a fallback path to the origin server for when edge functions fail due to platform issues or resource limits.
Deploying globally when data is in one region. If most traffic is regional and the DB is in US-East, 200+ edge locations add no benefit. Use preferredRegion to deploy near the database for data-heavy pages.
Source
Process
- Read the instructions and examples in this document.
- Apply the patterns to your implementation, adapting to your specific context.
- Verify your implementation against the details and edge cases listed above.
Harness Integration
- Type: knowledge — this skill is a reference document, not a procedural workflow.
- No tools or state — consumed as context by other skills and agents.
Success Criteria
- Edge functions achieve <100ms TTFB for users in the primary geographic region.
- Edge runtime constraints are respected (no Node.js-only APIs in edge functions).
- Data access strategy accounts for edge-to-origin latency (KV, replicas, or regional deployment).
- Edge caching is configured with appropriate TTLs and invalidation mechanisms.
- Fallback to origin is implemented for edge function failures.
1---2name: perf-edge-rendering3description: Edge Rendering4metadata:5 source: https://skillmd.com/skills/intense-visions/perf-edge-rendering6---7# Edge Rendering89> Master edge rendering — deploying server-side rendering to edge locations for minimal latency, understanding edge runtime constraints, regional deployment strategies, edge middleware patterns, data locality considerations, and platform-specific optimization for Cloudflare Workers, Vercel Edge, and Deno Deploy.1011## When to Use1213- Users are geographically distributed and origin server latency varies by region14- TTFB is high for users far from the origin server (>200ms)15- Server-side rendering is needed but origin-only deployment adds latency16- Personalization (A/B tests, geo-targeting, localization) needs to happen before content delivery17- Authentication and authorization checks could run closer to the user18- API responses could be transformed or enriched at the edge19- Static generation is too stale but full origin SSR adds unnecessary latency20- Edge middleware is needed for redirects, rewrites, or header manipulation21- A global application needs consistent sub-100ms TTFB worldwide22- Feature flags need to be evaluated before page rendering without a client-side flash2324## Instructions25261. **Understand edge versus origin architecture.** Edge functions run in data centers close to the user (200+ locations) instead of a single origin:2728 ```29 Origin-only SSR:30 User (Tokyo) → CDN → Origin (US-East) → DB → Render → Response31 Network RTT: ~150ms | TTFB: ~350ms3233 Edge Rendering:34 User (Tokyo) → Edge (Tokyo) → Render → Response35 Network RTT: ~5ms | TTFB: ~50ms3637 Edge + Origin Data:38 User (Tokyo) → Edge (Tokyo) → Origin API (US-East) → Edge Render → Response39 Network RTT: ~5ms + ~150ms (data) | TTFB: ~200ms40 (Still faster: user sees shell immediately via streaming)41 ```42432. **Deploy edge functions on Cloudflare Workers.** Workers run on V8 isolates with sub-millisecond cold starts:4445 ```typescript46 // src/worker.ts — Cloudflare Worker47 export default {48 async fetch(request: Request, env: Env): Promise<Response> {49 const url = new URL(request.url);5051 // Edge-rendered HTML52 const html = await renderPage(url.pathname, {53 userCountry: request.cf?.country,54 userCity: request.cf?.city,55 });5657 return new Response(html, {58 headers: {59 'Content-Type': 'text/html; charset=utf-8',60 'Cache-Control': 'public, max-age=60, s-maxage=300',61 },62 });63 },64 };6566 // wrangler.toml67 // name = "my-app"68 // main = "src/worker.ts"69 // compatibility_date = "2024-01-01"70 ```71723. **Use Vercel Edge Runtime for Next.js.** Mark routes to run on the edge instead of Node.js:7374 ```typescript75 // app/api/geo/route.ts — Edge API route76 export const runtime = 'edge';7778 export async function GET(request: Request) {79 const country = request.headers.get('x-vercel-ip-country') || 'US';80 const city = request.headers.get('x-vercel-ip-city') || 'Unknown';8182 return Response.json({83 country,84 city,85 timestamp: Date.now(),86 });87 }8889 // middleware.ts — geo-redirects and A/B tests at the edge90 // Use request.geo?.country for geo-routing, cookies for A/B persistence91 // Configure matcher to exclude static assets: /((?!_next/static|favicon).*)92 ```93944. **Handle edge runtime constraints.** Edge runtimes use a limited Web API subset (no Node.js APIs):9596 ```typescript97 // Available at the edge:98 // - fetch(), Request, Response, Headers99 // - URL, URLSearchParams, URLPattern100 // - crypto.subtle, crypto.getRandomValues101 // - TextEncoder, TextDecoder102 // - structuredClone, atob, btoa103 // - setTimeout (limited), Promises, async/await104 // - Web Streams API105106 // NOT available at the edge:107 // - fs, path, child_process (no file system)108 // - Buffer (use Uint8Array instead)109 // - net, http (use fetch instead)110 // - Most npm packages that use Node.js APIs111112 // Edge-compatible alternatives:113 // Database: Neon serverless, PlanetScale, Turso (HTTP-based)114 // KV Store: Cloudflare KV, Vercel KV, Upstash Redis115 // ORM: Drizzle (with HTTP adapter), Prisma (with Accelerate)116 ```1171185. **Implement edge caching for dynamic content.** Cache rendered pages at the edge with smart invalidation:119120 ```typescript121 // Cloudflare Workers — Cache API122 async function handleRequest(request: Request): Promise<Response> {123 const cache = caches.default;124 const cacheKey = new Request(request.url, request);125126 // Check edge cache127 let response = await cache.match(cacheKey);128 if (response) {129 return response;130 }131132 // Render at the edge133 const html = await renderPage(request);134 response = new Response(html, {135 headers: {136 'Content-Type': 'text/html',137 'Cache-Control': 'public, s-maxage=300', // cache at edge for 5 min138 },139 });140141 // Store in edge cache (non-blocking)142 const cacheResponse = response.clone();143 await cache.put(cacheKey, cacheResponse);144145 return response;146 }147 ```1481496. **Manage data locality.** Edge rendering is fast only if data access is also fast. Strategies for reducing data latency:150151 ```typescript152 // Strategy 1: Edge KV for read-heavy data153 // Cloudflare KV: eventually consistent, <10ms reads globally154 const config = await env.CONFIG_KV.get('site-config', 'json');155156 // Strategy 2: Edge-local database replicas157 // Turso (libSQL): read replicas in 30+ regions158 // Read from local replica, write to primary159 import { createClient } from '@libsql/client';160 const db = createClient({161 url: 'libsql://db-name-region.turso.io',162 authToken: '...',163 });164165 // Strategy 3: Cache at the edge, fetch from origin166 // Best for: data that changes infrequently, high read volume167 const data = await env.CACHE.get(key, 'json');168 if (!data) {169 const fresh = await fetch('https://origin.example.com/api/data');170 await env.CACHE.put(key, await fresh.text(), { expirationTtl: 300 });171 }172173 // Strategy 4: Smart routing — render at the edge closest to the database174 // Vercel: configure function regions to match database location175 // export const preferredRegion = 'iad1'; // US East, near the DB176 ```1771787. **Monitor edge function performance.** Instrument with `Date.now()` timing, log the edge location (`request.cf?.colo` on Cloudflare), and always fall back to `fetch(request)` on error. Track cold start frequency, P99 execution time, and cache hit rates via platform analytics (Cloudflare Analytics Engine, Vercel Analytics).179180## Details181182### Edge Runtime Cold Starts183184Cloudflare Workers use V8 isolates with sub-millisecond cold starts; Vercel Edge Functions ~5ms. Both are far faster than Lambda (100-1000ms). Trade-off: no file system, no native modules, limited memory (128MB), and limited CPU time (10-50ms free tier). Design edge functions to be lightweight.185186### Worked Example: Cloudflare Blog187188Runs entirely on Workers with streaming SSR. Blog posts render from Markdown in Workers KV, cached at the edge. First request renders and caches; subsequent requests serve in <5ms globally. Webhook-based cache purging on content updates. Result: <50ms TTFB worldwide, zero origin load for reads.189190### Worked Example: Shopify Oxygen191192Deploys Remix storefronts to Cloudflare Workers. Edge rendering takes 20-50ms, Storefront API responds in 50-100ms, yielding 70-150ms total TTFB vs 200-400ms origin-only. Stale-while-revalidate caching drops frequently-accessed pages to <10ms TTFB.193194### Anti-Patterns195196**Edge rendering with origin-only databases.** If every request queries a database in US-East, the edge latency advantage is negated. Use edge-local data stores (KV, replicas) or accept the benefit is limited to non-data-dependent content.197198**Heavy computation at the edge.** Edge runtimes have strict CPU time limits (10-50ms on free tiers). Offload image processing and heavy transformations to origin functions. Use the edge for lightweight rendering, routing, and personalization.199200**Not falling back to origin on edge failure.** Always implement a fallback path to the origin server for when edge functions fail due to platform issues or resource limits.201202**Deploying globally when data is in one region.** If most traffic is regional and the DB is in US-East, 200+ edge locations add no benefit. Use `preferredRegion` to deploy near the database for data-heavy pages.203204## Source205206- Cloudflare Workers — https://developers.cloudflare.com/workers/207- Vercel Edge Functions — https://vercel.com/docs/functions/edge-functions208- Deno Deploy — https://deno.com/deploy209- web.dev: Edge Rendering — https://web.dev/articles/rendering-on-the-web#edge_rendering210211## Process2122131. Read the instructions and examples in this document.2142. Apply the patterns to your implementation, adapting to your specific context.2153. Verify your implementation against the details and edge cases listed above.216217## Harness Integration218219- **Type:** knowledge — this skill is a reference document, not a procedural workflow.220- **No tools or state** — consumed as context by other skills and agents.221222## Success Criteria223224- Edge functions achieve <100ms TTFB for users in the primary geographic region.225- Edge runtime constraints are respected (no Node.js-only APIs in edge functions).226- Data access strategy accounts for edge-to-origin latency (KV, replicas, or regional deployment).227- Edge caching is configured with appropriate TTLs and invalidation mechanisms.228- Fallback to origin is implemented for edge function failures.