Skip to content

Add CORS middleware for Firefox localhost development compatibility #744

@chris-tse

Description

@chris-tse

Add CORS support for localhost development in Firefox

Firefox enforces stricter CORS policies than other browsers, even for localhost origins. The opencode server currently has no CORS middleware configured, causing Firefox to block cross-origin requests

Current Behavior

  • Chrome/Safari: Requests from localhost:5173localhost:4096 work fine
  • Firefox/Zen: Same requests fail with CORS error
    Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:4096/session. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 404.
    

Proposed Solution

Add CORS middleware to the Hono server with localhost-specific configuration.

import { cors } from "hono/cors"

function app() {
  const app = new Hono()

  const result = app
    .onError((err, c) => {
      // ... existing error handling
    })
    .use(
      "*",
      cors({
        origin: (origin) => {
          // Allow localhost origins on any port for development
          const localhostPattern = /^https?:\/\/localhost(:\d+)?$/
          const localhostIPPattern = /^https?:\/\/127\.0\.0\.1(:\d+)?$/

          if (
            localhostPattern.test(origin) ||
            localhostIPPattern.test(origin)
          ) {
            return origin
          }

          return null // Reject other origins
        },
        allowMethods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
        allowHeaders: ["Content-Type", "Authorization", "X-Requested-With"],
        exposeHeaders: ["Content-Length", "X-Request-ID"],
        credentials: true,
        maxAge: 86400, // 24 hours for development
      }),
    )
    .use(async (c, next) => {
      // ... existing logging middleware
    })
  // ... rest of route definitions

  return result
}

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions