CORS Safe Preflight Handler

Configure CORS with explicit origin allowlist credential support and preflight caching for safe cross-origin API access.

JavascriptSecurity Boundaries

Code

javascriptsnippet
1 line
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

FAQ

Are there dependencies to manage?
No. There are no dependencies to declare or install. The file defines `corsMiddleware`, `cors` at load time.