Lambda@Edge primer
Lambda@Edge lets you run Node.js or Python at CloudFront points of presence, mutating requests and responses microseconds before they hit the viewer. This recipe walks through a Meridian deployment that authenticates JWTs, rewrites paths, and streams structured logs back to the control plane without ever touching origin.
1. Pick the right trigger
CloudFront fires Lambda@Edge at four points: viewer-request,origin-request,origin-response, andviewer-response. For auth gates pick viewer-request, the earliest hook, before CloudFront looks at its cache.
2. Keep the bundle skinny
The viewer triggers cap at 1 MB unzipped and 128 MB memory. No native modules, no SDK bloat. Inline a JWKS cache, sign with a KMS-fronted key, and let CloudFront edge-cache the JWKS response by setting a long Cache-Control on its origin.
3. Wire the handler
Export a single async handler that returns the mutated request. Reject with a synthetic 403 response when the token is missing or stale.
exports.handler = async (event) => {
const req = event.Records[0].cf.request;
const auth = req.headers.authorization?.[0]?.value;
if (!auth) {
return {
status: '403',
statusDescription: 'Forbidden',
body: 'Missing token'
};
}
const claims = await verifyJwt(auth.replace('Bearer ', ''));
req.headers['x-meridian-user'] = [{
key: 'X-Meridian-User',
value: claims.sub
}];
return req;
};