| 1 | import type { MiddlewareHandler } from "hono"; |
| 2 | import { cors } from "hono/cors"; |
| 3 | import type { AppEnv } from "../env"; |
| 4 | |
| 5 | // CORS with credentials: only origins listed in ALLOWED_ORIGINS get an |
| 6 | // Access-Control-Allow-Origin header, and it always echoes the exact origin |
| 7 | // (never "*", which is incompatible with cookies). |
| 8 | export const corsMiddleware: MiddlewareHandler<AppEnv> = (c, next) => { |
| 9 | const allowed = (c.env.ALLOWED_ORIGINS ?? "") |
| 10 | .split(",") |
| 11 | .map((s) => s.trim()) |
| 12 | .filter(Boolean); |
| 13 | return cors({ |
| 14 | origin: (origin) => (allowed.includes(origin) ? origin : null), |
| 15 | credentials: true, |
| 16 | allowMethods: ["GET", "POST", "DELETE", "OPTIONS"], |
| 17 | allowHeaders: ["Content-Type", "Authorization"], |
| 18 | maxAge: 86400, |
| 19 | })(c, next); |
| 20 | }; |
| 21 |