Edge computing in practice: middleware and redirects
When someone talks about edge computing, everyone thinks about complex infrastructure. Datacenters around the world, distributed architecture, things that Netflix does. The truth is you can use it on your site right now. No complexity.
Edge computing is simply code that runs closer to the user instead of everything running on a central server. Your user is in Rio, server is in Rio. Your user is in New York, code runs near there. Latency drops dramatically.
Middleware in Astro
Astro 3.0+ supports middleware natively. It’s a file that runs before any route is loaded.
// src/middleware.ts
import { defineMiddleware } from "astro:middleware";
export const onRequest = defineMiddleware((context, next) => {
// Auth check
if (!context.cookies.has("session")) {
return new Response("Unauthorized", { status: 401 });
}
return next();
});
This runs on the edge if you’re on Vercel. Fast. No cold start. When someone tries to access your page without authentication, middleware blocks them before the site does any processing.
I used this on a clinic with a booking system. User not authenticated? Redirects. User is dentist? Shows different dashboard. All on the edge, before any React component renders.
Geo-based redirects
Vercel Edge Functions let you know the user’s location. Information comes from the cf-ipcountry header if you’re behind Cloudflare, or x-vercel-ip-country on Vercel.
export default function middleware(request) {
const country = request.headers.get("x-vercel-ip-country");
if (country === "BR") {
return NextResponse.rewrite(new URL("/pt", request.url));
}
return NextResponse.rewrite(new URL("/en", request.url));
}
Your user in Rio sees the site in Portuguese. Same user travels to London, sees Portuguese site (because UK IP also matches). Travels to Tokyo, might see English or Portuguese depending on your logic.
This is powerful for SEO because Google can crawl both versions of the site on the same URL.
A/B testing on the edge
Traditional A/B testing runs in the browser. You load the page, execute JavaScript, show version A or B. Problem is this causes “flicker”: user sees default version for 100ms, then it changes. Terrible UX.
Edge A/B testing shows the correct version right away because the redirect happens before the page renders.
export default function middleware(request) {
const abTest = Math.random() > 0.5 ? "a" : "b";
const response = NextResponse.next();
response.cookies.set("ab_variant", abTest);
if (abTest === "a") {
return NextResponse.rewrite(new URL("/pages/variant-a", request.url));
}
return NextResponse.rewrite(new URL("/pages/variant-b", request.url));
}
Now you’re testing design, copy, conversion flow. No flicker. No JavaScript running on the client. Cleaner metrics.
Auth without cold start
Traditionally you make a request to an auth endpoint, wait for response, validate JWT. Everything running on your server.
On the edge you validate the token inline. No roundtrip anywhere.
import { jwtVerify } from "jose";
const secret = new TextEncoder().encode(process.env.JWT_SECRET);
export async function validateToken(token) {
try {
const verified = await jwtVerify(token, secret);
return verified.payload;
} catch (err) {
return null;
}
}
This code runs on the edge, validates in microseconds, no roundtrip to database. It’s blazingly fast.
For clinics where booking is private per user, I put this check on the edge. Someone tries to bypass? Blocked before page loads.
Vercel Edge Functions vs Cloudflare Workers
Vercel Edge Functions uses V8 runtime, it’s pure JavaScript. Easy to deploy if you already use Vercel. Costs are included in the plan, no additional charges for most use cases.
Cloudflare Workers is cheaper (free up to 100k requests/day) and faster. You can do aggressive caching. Problem is it doesn’t run Ruby, only JavaScript. And integration with your site varies.
I use Vercel Edge Functions for sites on Vercel. Cloudflare Workers for sites elsewhere that need edge caching.
Real use cases
Clinic website that needs to show different hours by timezone. Edge middleware detects user timezone, injects correct hours.
E-commerce that wants to show price in local currency. Detects country, converts automatically. No JavaScript on the client.
Feature flags system. You release new feature to only 10% of users. Control flow on the edge, without hitting the database.
The trap
Edge computing can make you refactor code unnecessarily. First ask: is latency your problem? Does your site load slowly?
If yes, edge computing helps. If your site loads in two seconds, edge computing won’t work magic.
Start with something simple. A geo redirect. An auth check. Then expand.
- Check if your deploy is Vercel, Netlify or Cloudflare
- Configure basic auth middleware
- Add geo-redirect if you have multiple languages
- Implement simple A/B test
- Monitor latency before and after
- Document your edge strategy
Edge computing is a tool, not magic. Use it when it makes sense.
Monitoring edge functions
One thing nobody talks about: edge functions fail silently. Error in middleware? User gets 500 error. You’re fine without knowing.
Vercel provides logs. Always turned it on. See errors middleware is throwing.
Cloudflare too. Dashboard shows requests that failed.
Set up alerts. If an edge function fails 10 times in 1 hour, notifies me. Because edge is running on many machines at once, easy to not notice.
Cost of edge functions
Vercel: included in plan, no additional cost for most.
Cloudflare: free up to 100k requests/day. Above that, you pay. But cheap, like USD 0.50 per 1M requests.
Never paid for Cloudflare Workers. Always stay under 100k.
Edge computing isn’t expensive. It’s dirt cheap.
Debugging edge functions
Error in edge is hard to debug. It’s not local. Running on remote server.
Tip: do aggressive logging. Each step of middleware, log it.
export const onRequest = defineMiddleware((context, next) => {
console.log('Middleware start')
const token = context.cookies.get('auth')
console.log('Token:', token)
if (!token) {
console.log('No token, returning 401')
return new Response("Unauthorized", { status: 401 })
}
console.log('Token found, calling next')
return next()
})
Then see logs in Vercel dashboard. Understand why it failed.
Another thing: test locally first. Vercel provides astro dev that executes middleware locally. Test there before deploying.
Real edge performance
Latency with edge: 50ms. Latency without edge (origin): 300ms. Difference is noticeable.
But only if you’re doing operation that matters on the edge. If middleware just checks JWT with complex operation, you don’t gain much.
If it’s simply a redirect, you gain a lot.
Measurement: I once added geo-redirect with edge. Initial response time? 100ms faster.
Then removed it to test. Went back to original. Put it back on.
Real difference, measurable, noticeable to user.
Roadmap for edge
Start with one thing. Auth check or geo-redirect. Deploy, test.
Month 2: add A/B test.
Month 3: think about feature flags.
Don’t try to do everything at once. Edge computing has cognitive overhead. Each thing you put there is one less thing to think about on the server.
But well planned, edge is really cheap.
Read also: Cloudflare as complete infrastructure | Deploy beyond Vercel | Core Web Vitals in 2026