Skip to main content
Edge Auth: Validating JWTs Without Origin Round-Trips

Edge Auth: Validating JWTs Without Origin Round-Trips

KU
· Founder & Chief Editor
• 8 min read•Updated •28 views

Verifying signed tokens at the edge with WebCrypto blocks bad traffic early and saves a full origin hop. Here's the pattern we ship, and the traps.

Key takeaways

  • Verify JWTs at the edge by caching the issuer's JWKS for about ten minutes and checking each signature with WebCrypto, then validating alg, exp, iss and aud.
  • Bad tokens get a 401 at the nearest POP without touching origin.
  • Keep tokens short-lived so you never need a per-request call to the auth server.

Validate JWTs at the edge by fetching the issuer's JWKS once, caching it for about ten minutes, and verifying each token with WebCrypto's crypto.subtle.verify, then checking alg, exp, iss and aud. Bad tokens die at the nearest POP with a 401, good ones reach origin already trusted, and nothing phones home per request.

Verified against

RFC 7519 (JWT), RFC 7517 (JWK) and RFC 8725 (JWT Best Current Practices, BCP 225), against the MDN SubtleCrypto.verify reference and the Cloudflare Workers Web Crypto docs. Checked October 2026.

We had an API that spent real money answering requests it should have rejected. Every call hit the origin, the origin decoded a bearer token, saw it was expired, and returned a 401. That's a full round-trip to your compute region to say "no." Under a credential-stuffing burst it's also your origin doing the work an attacker wants it to do.

Moving that check to the edge fixed both problems. A request with a bad or missing token now dies at the nearest POP, tens of milliseconds from the user, and never touches origin. A request with a good token arrives at origin already trusted, so the origin skips its own verification. The math is simple: one fewer hop on the happy path, and zero hops on the reject path.

Verifying a JWT at the edge with WebCrypto

Edge runtimes (Cloudflare Workers, Vercel Edge, Deno Deploy) don't reliably give you Node's crypto or your favorite JWT library (Workers only exposes Node's module behind the nodejs_compat flag). They all give you the WebCrypto SubtleCrypto API, which is enough. A JWT is three base64url segments: header, payload, signature. You verify that the signature covers header.payload using the issuer's public key.

The public keys live at the issuer's JWKS endpoint (/.well-known/jwks.json for most providers). You fetch it once, cache it, and match the token's kid header to the right key.

JavaScript
// jwks.js: fetch + cache the issuer's public keys
const JWKS_URL = "https://issuer.example.com/.well-known/jwks.json";
const cache = { keys: new Map(), expires: 0 };

async function getKey(kid) {
  if (Date.now() > cache.expires) {
    const res = await fetch(JWKS_URL, { cf: { cacheTtl: 600 } });
    const { keys } = await res.json();
    cache.keys.clear();
    for (const jwk of keys) {
      const algo = jwk.kty === "RSA"
        ? { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }
        : { name: "ECDSA", namedCurve: "P-256", hash: "SHA-256" };
      const key = await crypto.subtle.importKey("jwk", jwk, algo, false, ["verify"]);
      cache.keys.set(jwk.kid, { key, kty: jwk.kty, alg: jwk.kty === "RSA" ? "RS256" : "ES256" });
    }
    cache.expires = Date.now() + 10 * 60 * 1000; // 10 min TTL
  }
  return cache.keys.get(kid);
}

Now the verify step. Decode, check the signature, then check the claims. Order matters: never trust a claim before you've verified the signature, and never let the token's own alg header pick the algorithm. RFC 8725 requires the verifier to pin one algorithm per key, which is what the bad alg check does.

JavaScript
// verify.js
function b64urlToBytes(s) {
  const pad = "=".repeat((4 - (s.length % 4)) % 4);
  const b = atob((s + pad).replace(/-/g, "+").replace(/_/g, "/"));
  return Uint8Array.from(b, (c) => c.charCodeAt(0));
}

export async function verifyJwt(token, { aud, iss }) {
  const [h, p, s] = token.split(".");
  if (!h || !p || !s) throw new Error("malformed");

  const header = JSON.parse(new TextDecoder().decode(b64urlToBytes(h)));
  const entry = await getKey(header.kid);
  if (!entry) throw new Error("unknown kid");
  if (header.alg !== entry.alg) throw new Error("bad alg"); // RFC 8725 3.1

  const algo = entry.kty === "RSA"
    ? { name: "RSASSA-PKCS1-v1_5" }
    : { name: "ECDSA", hash: "SHA-256" };

  const data = new TextEncoder().encode(`${h}.${p}`);
  const ok = await crypto.subtle.verify(algo, entry.key, b64urlToBytes(s), data);
  if (!ok) throw new Error("bad signature");

  const claims = JSON.parse(new TextDecoder().decode(b64urlToBytes(p)));
  const now = Math.floor(Date.now() / 1000);
  if (typeof claims.exp !== "number" || now >= claims.exp) throw new Error("expired");
  if (claims.nbf && now < claims.nbf) throw new Error("not yet valid");
  if (iss && claims.iss !== iss) throw new Error("bad iss");
  if (aud && ![].concat(claims.aud).includes(aud)) throw new Error("bad aud");

  return claims;
}

One gotcha for ECDSA: WebCrypto expects the raw r||s signature that JWTs already use, so ES256 works directly. If you ever verify a DER-encoded signature you'll have to convert it. RS256 is the boring, dependable default and what we run in production.

The Worker middleware

JavaScript
// worker.js
export default {
  async fetch(request, env, ctx) {
    const auth = request.headers.get("authorization") || "";
    const token = auth.startsWith("Bearer ") ? auth.slice(7) : null;
    if (!token) return new Response("unauthorized", { status: 401 });

    try {
      const claims = await verifyJwt(token, {
        aud: env.API_AUDIENCE,
        iss: env.ISSUER,
      });
      // Trusted. Pass identity to origin so it skips re-verification.
      const req = new Request(request);
      req.headers.set("x-user-id", claims.sub);
      return fetch(req);
    } catch (err) {
      return new Response("unauthorized", { status: 401 });
    }
  },
};

Session cookies instead of bearer tokens

Browser traffic usually carries a session cookie, not an Authorization header. If your session token is itself a signed JWT (a stateless session), the exact same verify function works: read it from request.headers.get("cookie"), parse out your cookie name, and hand the value to verifyJwt. This is the pattern we prefer for first-party web apps: a short-lived signed cookie the edge can check offline, refreshed against your auth server only when it nears expiry.

Key rotation without breaking

Issuers rotate signing keys. The kid in the token header is how you survive it: during rotation the JWKS endpoint publishes both the old and new keys, so tokens signed with either still verify. Your only job is to not cache the JWKS forever. A 10-minute TTL means a rotated key is picked up within 10 minutes, which is fine because the old key stays published far longer than that. If verification fails on an unknown kid, force one JWKS refresh before giving up. That covers the rare case where rotation outpaced your cache.

What not to do at the edge

Don't call your auth server on every request. If the edge phones home to validate each token, you've reintroduced the round-trip you came to delete, plus a new dependency in the hot path. The whole point of a signed token is offline verification.

Don't do full session lookups against a single-region store from the edge. A Worker in Singapore hitting a Postgres session table in Virginia is slower than just going to origin. If you need server-side session state, either replicate it to the edge (Cloudflare KV, Durable Objects, a replicated store) or keep sessions stateless with short-lived tokens and accept that revocation lags by the token lifetime. We keep access tokens at 5 to 15 minutes so a compromised token expires fast without a revocation list.

Don't leave origin reachable around the edge. The origin trusts x-user-id because only the Worker should be able to set it. If an attacker can hit the origin hostname directly, they send their own x-user-id: admin and skip auth entirely. Lock origin to edge traffic with mutual TLS (Cloudflare calls it Authenticated Origin Pulls), a tunnel, or a shared secret header the Worker adds, and reject everything else.

This pairs naturally with keyless authentication: no long-lived secret sits at the edge, only public keys. For where else this kind of check belongs, see our edge computing playbook.

Questions people ask

Can you verify a JWT in Cloudflare Workers without a library?

Yes. Workers implements the Web Crypto API, including RSASSA-PKCS1-v1_5, RSA-PSS, ECDSA and Ed25519 for signing and verification. Import the issuer's JWK with crypto.subtle.importKey, verify the signature over header.payload with crypto.subtle.verify, then check the claims yourself. The whole verifier is about 40 lines, and a maintained JWT library built on Web Crypto works too if you'd rather not own it.

How do you handle JWKS key rotation at the edge?

Match the token's kid header against a cached JWKS and refresh the cache on a short TTL, around ten minutes. Issuers publish old and new keys side by side during rotation, so either signature verifies. When a kid is unknown, force one refresh before rejecting, and rate-limit that refresh so a flood of junk kid values can't hammer the issuer.

How do you revoke a JWT that the edge validates offline?

You mostly don't, which is why access tokens should live 5 to 15 minutes. A stolen token works until exp. If you need faster revocation, keep a denylist of token IDs (jti) or user IDs in an edge-replicated store such as Workers KV and check it after the signature. KV is eventually consistent, so revocation still lags by the propagation delay, and the check adds a read to every request, so only pay for it on sensitive routes.

The call we'd make

Verify signed JWTs at the edge with WebCrypto, cache the JWKS on a short TTL, and reject bad traffic before it costs you an origin hop. Keep tokens short-lived and stateless so the edge never has to phone home. Reach for a replicated session store only when you genuinely need instant revocation, and know you're paying for it. For most APIs, offline signature verification at the POP is the cheapest security win on the table.

Sources

Explore topics:SecurityCloud
React
Share this post
Cite this article
Plain text

Kiril Urbonas (2026). Edge Auth: Validating JWTs Without Origin Round-Trips. DevOpsNess. Updated 2026-10-31. https://www.devopsness.com/blog/edge-auth-validating-jwts-without-origin-round-trips

Markdown

[Edge Auth: Validating JWTs Without Origin Round-Trips](https://www.devopsness.com/blog/edge-auth-validating-jwts-without-origin-round-trips) (Kiril Urbonas, DevOpsNess, updated 2026-10-31)

KU

Kiril Urbonas

Founder & Chief Editor

586 articles
View all articles by Kiril Urbonas

You might have missed

Evergreen posts worth revisiting.