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();};}Report a problem with this exampleOpens a pre-filled issue on GitHub.