Skip to content
CMO & CTO
CMO & CTO

Closing the Bridge Between Marketing and Technology, By Luis Fernandez

  • Digital Experience
    • Experience Strategy
    • Experience-Driven Commerce
    • Multi-Channel Experience
    • Personalization & Targeting
    • SEO & Performance
    • User Journey & Behavior
  • Marketing Technologies
    • Analytics & Measurement
    • Content Management Systems
    • Customer Data Platforms
    • Digital Asset Management
    • Marketing Automation
    • MarTech Stack & Strategy
    • Technology Buying & ROI
  • Software Engineering
    • Software Engineering
    • Software Architecture
    • General Software
    • Development Practices
    • Productivity & Workflow
    • Code
    • Engineering Management
    • Business of Software
    • Code
    • Digital Transformation
    • Systems Thinking
    • Technical Implementation
  • About
CMO & CTO

Closing the Bridge Between Marketing and Technology, By Luis Fernandez

Edge Functions and the New Web Stack

Posted on October 14, 2022 By Luis Fernandez

The web just got closer to your users.

We have been chasing speed with smarter builds, smaller bundles, and more static output, and that got us far. Then edge functions arrived, turning the CDN from a dumb cache into a smart runtime. Code runs near the visitor and shaves off the trip to a central server. That simple shift changes product UX and campaign results in very real ways.

As developers we gain low latency decisions at the request level. As marketers we get faster pages, higher quality scores, and more room for personalization without tanking Core Web Vitals. Edge functions are not the future, they are showing up in our toolchains right now. If you ship with Next.js, Netlify, Cloudflare, or Deno, you already see the knobs.

This is the new web stack, and it runs on the edge.

What is an edge function and why should you care

Think of an edge function as a tiny server that lives in a CDN point of presence. It gets the request first, can read headers, cookies, geo, and device hints, then decide what to do. It can rewrite, cache, fetch from an origin, or craft a response on the spot. No origin round trip means lower TTFB and more control over the first byte your user sees.

Cloudflare calls them Workers. Vercel wires them into Next.js middleware. Netlify ships them with a familiar project structure and Deno under the hood. The runtime is web standard in most cases: fetch, Request, Response, URL, crypto, and some limits. That means you write browser style code on the server, and you keep it small.

Speed at the edge beats power far away when the job is small.

The SEO angle: Core Web Vitals start faster when the edge answers first

Search does not reward intent, it rewards delivery. Time to first byte anchors the rest of the journey. If your first byte is coming from a city down the road, your LCP and FID have a better shot. With edge functions you can serve a cached HTML shell, inject a user segment in a cookie, and stream content while the app hydrates. That combo feels quick and scores better.

Marketers care since ad spend depends on speed. Lower TTFB nudges quality score up which drops CPC. It also reduces bounce on cold traffic. Fast first paint keeps people around long enough for your message to land. The edge gives you that first byte advantage without a heavy rebuild of your backend.

Speed gets the click, relevance keeps the visit.

Common use cases that pay off right away

Personalization at the route layer: pick copy, price, or currency by geo and cookie. A B testing without client side flicker: split at the edge and cache per variant. Feature flags that decide before the origin: avoid wasted work down the stack. Smart redirects for campaigns and short links that respect device and locale.

You can also protect origin capacity during launches. Rate limit at the edge and show a queue page. You can sign requests, strip secrets, and do bot checks before hitting your app. Edge functions are best at quick checks and quick choices. Keep the work brief and lean on caches.

Think decisions, not heavy lifting.

A tiny Cloudflare Worker for geo split and cache

Workers expose web APIs, so it feels like writing for the browser with super powers. Here is a small worker that sends visitors to a regional page and sets a clean cache key per variant.

export default {
  async fetch(request, env, ctx) {
    const url = new URL(request.url);
    const country = request.cf && request.cf.country || "US";

    // simple two bucket split by country
    const variant = country === "DE" ? "eu" : "us";

    // set a cookie so future hops stay sticky
    const headers = new Headers();
    headers.set("Set-Cookie", `region=${variant}; Path=/; Max-Age=2592000; SameSite=Lax`);

    // rewrite to variant path and cache by region
    url.pathname = `/${variant}${url.pathname}`;
    const cacheKey = new Request(url.toString(), request);
    const cache = caches.default;

    let res = await cache.match(cacheKey);
    if (!res) {
      res = await fetch(cacheKey);
      res = new Response(res.body, res);
      res.headers.set("Cache-Control", "public, s-maxage=86400, stale-while-revalidate=604800");
      ctx.waitUntil(cache.put(cacheKey, res.clone()));
    }

    // add the cookie without breaking cache
    const final = new Response(res.body, res);
    headers.forEach((v, k) => final.headers.append(k, v));
    return final;
  }
};

This worker reads geo data from the request, picks a variant, and saves the choice in a cookie. The cache key includes the new path so you avoid mixed content. One worker, no origin hit on repeat visits. That is money in the bank for both speed and cost.

Small code, big effect.

Next.js middleware at the edge

Next.js ships middleware that runs before a route handler. On Vercel you can mark it for the edge runtime and use standard web APIs. This example does a clean A B split and keeps the variant stable with a cookie while avoiding client side flicker.

// file: middleware.ts
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";

export const config = {
  matcher: ["/", "/pricing"]
};

export function middleware(req: NextRequest) {
  const url = req.nextUrl.clone();
  const cookie = req.cookies.get("ab")?.value;

  const variant = cookie || (Math.random() < 0.5 ? "a" : "b");
  if (!cookie) {
    const res = NextResponse.next();
    res.cookies.set("ab", variant, { path: "/", maxAge: 60 * 60 * 24 * 30, sameSite: "lax" });
    return res;
  }

  // rewrite without redirect, keeps the url bar clean
  url.pathname = `/${variant}${url.pathname}`;
  return NextResponse.rewrite(url);
}

This keeps the URL clean and the HTML stable per variant, which helps your cache and your analytics. Since the decision happens at request time you skip layout shift in the browser. That makes design tests feel native and more honest.

No flashes, just the right page.

What to watch out for

The edge runtime is lean. No Node specific modules. No giant binary deps. Keep payloads tiny and think in web APIs. You fetch, you read headers, you return a Response. If you need large data, fetch it from a store made for the edge like KV, Durable Objects, or a fast global cache. Save the heavy joins for a regional or central API.

Time limits are tight which is how you keep costs and latency down. Do not block on slow third parties at the edge. If you must call one, set a gentle timeout and fall back. Edge code should never be the longest pole in your request.

Keep it short and it flies.

Privacy by design with regional routing

Some data must stay in region. You can route requests to a data center in the right place before any personal data leaves the area. You can also strip or hash IDs at the edge so your origin only sees the minimum needed. This reduces audit stress and makes consent flows cleaner.

Set a cookie that records consent and check it at the edge. If it is missing, hold back tags and serve a version without external pixels. Once the user consents, you pass a safe header to your tag manager or page. Your team gets control without tying knots in your app.

Respect privacy and still move fast.

The new web stack, piece by piece

Build layer: Vite, Next.js, Remix, Astro. Render layer: static for most routes, server render where needed. Edge layer: routing, splits, feature flags, geo aware content, bot checks. API layer: serverless or long lived services for data and tasks. Storage: a mix of CDN cache, KV stores, and your main database.

The key is to push decisions to the earliest safe point. If the edge can answer, it should. If the origin must do work, keep it focused and cache the result. This shape gets you speed without losing flexibility. It also keeps teams from stepping on each other.

Do the right work in the right spot.

Tooling you can use today

Cloudflare Workers are rock solid and cover a wide map of cities. Deno Deploy feels like writing browser code with a server badge. Netlify ships edge functions with DX many of us already know. Vercel brings middleware to Next.js with a nice path for rewrites and headers. Astro ships islands and works well with partial hydration backed by edge routing.

Pick what fits your project. If you are on Next.js, middleware is the shortest path. If you want raw control, Workers are a great fit. If your team is deep on serverless already, the jump is small. The patterns carry over to any platform.

You do not need to start over, you just move closer.

Metrics and costs without guesswork

Edge functions cut origin trips which cuts infra load and lowers tail latency. That shows up in TTFB, LCP, and conversion rate. On the cost side, little CPU slices at the edge are cheap when the code is tight. The mistake is to push heavy work to the edge and fight the limits. Keep moves small and your bill stays friendly.

Watch your cache hit rate and p95. Ship observability from day one. Send timing headers and simple logs for variant tags and geo. If you can not see it, you can not tune it. The edge is fast but still needs a dashboard.

Measure first byte and design around it.

Marketing playbook: fast tests and local flavor

Run fast copy tests on hero sections without a single client side switch. Route paid traffic with clean UTMs to the right variant at the edge, then cache per variant. Serve currency and tax hints by country before React even boots. Tie this to a simple feature flag service and you get quick launches with low risk.

Want a campaign for a city level event. Add a rule at the edge for that region and point to a special page with a short cache TTL. When the event ends, flip the flag and the edge stops routing. Shipping becomes a rule change, not a deploy marathon.

Less friction means more experiments.

A compact checklist to get started

  • Pick one request: the home page or pricing, not everything.
  • Decide one thing: geo split, A B test, or a feature flag.
  • Write the edge function: keep it under one hundred lines.
  • Cache on purpose: set headers and think about the key.
  • Tag with headers: add X Variant and Region for logs and debug.
  • Measure: watch TTFB, LCP, and variant conversion.
  • Iterate: when the tiny thing works, add the next tiny thing.

Netlify Edge Functions quick start

Netlify uses Deno under the hood which gives you web APIs out of the box. Place your function in the edge functions folder and use a simple config to bind a path.

// file: netlify/edge-functions/geo.ts
export default async (req: Request) => {
  const url = new URL(req.url);
  const country = (req as any).geo?.country?.code || "US";
  const variant = country === "BR" ? "latam" : "global";

  if (url.pathname === "/") {
    url.pathname = `/${variant}`;
    return Response.redirect(url.toString(), 307);
  }

  return new Response("ok");
};

// file: netlify/edge-functions.json
[
  { "path": "/*", "function": "geo" }
]

This pattern is perfect for campaign hubs where geo matters. You can later swap the redirect for a rewrite to keep URLs stable. Start simple and grow with confidence.

First you route, then you refine.

Error handling and graceful fallbacks

The worst bug is a fast bug at scale. Wrap third party calls with timeouts and try catch. Send a plain HTML fallback if the world is on fire. Users forgive a simple page that loads, not a spinner that never ends. Edge functions make it easy to bail out early with a helpful message.

Also plan for cache stampedes. Seed the cache on deploy or use stale while revalidate to keep traffic smooth. A tiny queue in a Durable Object or a lock key in KV can save a bad day. Resilience is just as important as speed.

Fast is good, predictable is better.

Where this is going next

Runtimes are moving toward web standards, not platform quirks. More vendors are bringing storage closer to users, which makes edge decisions even smarter. Frameworks already speak the language with middleware hooks and adapters. You do not have to wait for a new platform to get gains.

Start with one edge rule that trims a second off your first byte. Feed that win back into your process. Soon the question becomes not can we run this at the edge, but should we. That is a great question to have on every feature.

The edge is not hype, it is a habit.


TLDR for busy teams: Edge functions let you make fast choices near the user. Use them for routing, tests, flags, and privacy checks. Keep code small, cache on purpose, and measure TTFB. Your users and your ad spend will thank you.

Digital Experience Marketing Technologies java

Post navigation

Previous post
Next post
  • Digital Experience (94)
    • Experience Strategy (19)
    • Experience-Driven Commerce (5)
    • Multi-Channel Experience (9)
    • Personalization & Targeting (21)
    • SEO & Performance (10)
  • Marketing Technologies (92)
    • Analytics & Measurement (14)
    • Content Management Systems (45)
    • Customer Data Platforms (4)
    • Digital Asset Management (8)
    • Marketing Automation (6)
    • MarTech Stack & Strategy (10)
    • Technology Buying & ROI (3)
  • Software Engineering (310)
    • Business of Software (20)
    • Code (30)
    • Development Practices (52)
    • Digital Transformation (21)
    • Engineering Management (25)
    • General Software (82)
    • Productivity & Workflow (30)
    • Software Architecture (85)
    • Technical Implementation (23)
  • 2025 (12)
  • 2024 (8)
  • 2023 (18)
  • 2022 (13)
  • 2021 (3)
  • 2020 (8)
  • 2019 (8)
  • 2018 (23)
  • 2017 (17)
  • 2016 (40)
  • 2015 (37)
  • 2014 (25)
  • 2013 (28)
  • 2012 (24)
  • 2011 (30)
  • 2010 (42)
  • 2009 (25)
  • 2008 (13)
  • 2007 (33)
  • 2006 (26)

Ab Testing Adobe Adobe Analytics Adobe Target AEM agile-methodologies Analytics architecture-patterns CDP CMS coding-practices content-marketing Content Supply Chain Conversion Optimization Core Web Vitals customer-education Customer Data Platform Customer Experience Customer Journey DAM Data Layer Data Unification documentation DXP Individualization java Martech metrics mobile-development Mobile First Multichannel Omnichannel Personalization product-strategy project-management Responsive Design Search Engine Optimization Segmentation seo spring Targeting Tracking user-experience User Journey web-development

©2025 CMO & CTO | WordPress Theme by SuperbThemes