CORS Safe Preflight Handler
Configure CORS with explicit origin allowlist credential support and preflight caching for safe cross-origin API access.
Code
export function corsMiddleware({allowedOrigins,credentials=true,maxAge=86400,allowedMethods=['GET','POST','PUT','PATCH','DELETE']}={}){return function cors(ctx,next){const origin=ctx.headers.origin;if(!origin||!allowedOrigins.includes(origin))return next();ctx.set('Access-Control-Allow-Origin',origin);if(credentials)ctx.set('Access-Control-Allow-Credentials','true');if(ctx.method==='OPTIONS'){ctx.set('Access-Control-Allow-Methods',allowedMethods.join(', '));ctx.set('Access-Control-Allow-Headers','Content-Type, Authorization');ctx.set('Access-Control-Max-Age',String(maxAge));ctx.status=204;return;}return next();};}Behavior line by line
Count the functions corsMiddleware and cors as the entire surface area of CORS Safe Preflight Handler.
Applying it
Signature: export function corsMiddleware({allowedOrigins,credentials=true,maxAge=86400,allowedMethods=['GET','POST','…
corsMiddleware is the public entry point; everything else in the file exists to support it.
Interactive Tools for This Topic
CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.CSP Header BuilderBuild a Content-Security-Policy header from per-directive sources, skipping empty ones and rejecting a blanket wildcard.Accept Header ParserParse an Accept header into media ranges with their quality values and specificity, sorted by preference for content negotiation debugging.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.
FAQ
- Are there dependencies to manage?
- No. There are no dependencies to declare or install. The file defines `corsMiddleware`, `cors` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.