Fix CORS configuration for Cloudflare Workers

Fixed CORS issue where 'Access-Control-Allow-Origin' header was missing.

The problem was that using `origin: '*'` with `credentials: true` is not
allowed by browsers. Changed to use a dynamic origin function that returns
the actual requesting origin, which is compatible with credentials mode.

Changes:
- Use dynamic origin function instead of static array
- Return requesting origin for wildcard (*) configuration
- Added 'Origin' to allowHeaders list
- Maintains compatibility with specific origin restrictions

This fixes CORS errors in browser-based clients.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2025-11-02 15:10:41 +01:00
parent f2bea69933
commit d993d6dbfc

View File

@@ -13,11 +13,22 @@ export interface AppConfig {
export function createApp(storage: Storage, config: AppConfig) {
const app = new Hono();
// Enable CORS
// Enable CORS with dynamic origin handling
app.use('/*', cors({
origin: config.corsOrigins,
origin: (origin) => {
// If no origin restrictions (wildcard), allow any origin
if (config.corsOrigins.length === 1 && config.corsOrigins[0] === '*') {
return origin;
}
// Otherwise check if origin is in allowed list
if (config.corsOrigins.includes(origin)) {
return origin;
}
// Default to first allowed origin
return config.corsOrigins[0];
},
allowMethods: ['GET', 'POST', 'OPTIONS'],
allowHeaders: ['Content-Type'],
allowHeaders: ['Content-Type', 'Origin'],
exposeHeaders: ['Content-Type'],
maxAge: 600,
credentials: true,