|
| 1 | +--- |
| 2 | +"@voltagent/server-hono": patch |
| 3 | +--- |
| 4 | + |
| 5 | +fix: correct CORS middleware detection to use actual function name 'cors2' |
| 6 | + |
| 7 | +Fixed a critical bug where custom CORS middleware was not being properly detected, causing both custom and default CORS to be applied simultaneously. This resulted in the default CORS (`origin: "*"`) overwriting custom CORS headers on actual POST/GET requests, while OPTIONS (preflight) requests worked correctly. |
| 8 | + |
| 9 | +## The Problem |
| 10 | + |
| 11 | +The middleware detection logic was checking for `middleware.name === "cors"`, but Hono's cors middleware function is actually named `"cors2"`. This caused: |
| 12 | + |
| 13 | +- Detection to always fail → `userConfiguredCors` stayed `false` |
| 14 | +- Default CORS (`app.use("*", cors())`) was applied even when users configured custom CORS |
| 15 | +- **Both** middlewares executed: custom CORS on specific paths + default CORS on `"*"` |
| 16 | +- OPTIONS requests returned correct custom CORS headers ✅ |
| 17 | +- POST/GET requests had custom headers **overwritten** by default CORS (`*`) ❌ |
| 18 | + |
| 19 | +## The Solution |
| 20 | + |
| 21 | +Updated the detection logic to check for the actual function name: |
| 22 | + |
| 23 | +```typescript |
| 24 | +// Before: middleware.name === "cors" |
| 25 | +// After: middleware.name === "cors2" |
| 26 | +``` |
| 27 | + |
| 28 | +Now when users configure custom CORS in `configureApp`, it's properly detected and default CORS is skipped entirely. |
| 29 | + |
| 30 | +## Impact |
| 31 | + |
| 32 | +- Custom CORS configurations now work correctly for **all** request types (OPTIONS, POST, GET, etc.) |
| 33 | +- No more default CORS overwriting custom CORS headers |
| 34 | +- Fixes browser CORS errors when using custom origins with credentials |
| 35 | +- Maintains backward compatibility - default CORS still applies when no custom CORS is configured |
| 36 | + |
| 37 | +## Example |
| 38 | + |
| 39 | +This now works as expected: |
| 40 | + |
| 41 | +```typescript |
| 42 | +import { VoltAgent } from "@voltagent/core"; |
| 43 | +import { honoServer } from "@voltagent/server-hono"; |
| 44 | +import { cors } from "hono/cors"; |
| 45 | + |
| 46 | +new VoltAgent({ |
| 47 | + agents: { myAgent }, |
| 48 | + server: honoServer({ |
| 49 | + configureApp: (app) => { |
| 50 | + app.use( |
| 51 | + "/agents/*", |
| 52 | + cors({ |
| 53 | + origin: "http://localhost:3001", |
| 54 | + credentials: true, |
| 55 | + }) |
| 56 | + ); |
| 57 | + }, |
| 58 | + }), |
| 59 | +}); |
| 60 | +``` |
| 61 | + |
| 62 | +Both OPTIONS and POST requests now return: |
| 63 | + |
| 64 | +- `Access-Control-Allow-Origin: http://localhost:3001` ✅ |
| 65 | +- `Access-Control-Allow-Credentials: true` ✅ |
0 commit comments