Skip to content

Document subtle CORS middleware allowedHeaders behavior #5935

@schickling

Description

@schickling

Summary

The HttpMiddleware.cors function has subtle but important behavior around allowedHeaders that isn't documented in the API or JSDoc comments.

Current Behavior

Looking at the implementation in packages/platform/src/internal/httpMiddleware.ts:

const opts = {
  allowedOrigins: ["*"],
  allowedMethods: ["GET", "HEAD", "PUT", "PATCH", "POST", "DELETE"],
  allowedHeaders: [],  // defaults to empty array
  ...options
}

const allowHeaders = (
  accessControlRequestHeaders: string | undefined
): ReadonlyRecord<string, string> | undefined => {
  if (opts.allowedHeaders.length === 0 && accessControlRequestHeaders) {
    return {
      vary: "Access-Control-Request-Headers",
      "access-control-allow-headers": accessControlRequestHeaders  // reflects back the request
    }
  }

  if (opts.allowedHeaders) {
    return {
      "access-control-allow-headers": opts.allowedHeaders.join(",")
    }
  }

  return undefined
}

Key insight: When allowedHeaders is an empty array (the default), the middleware reflects back whatever Access-Control-Request-Headers the client sends - effectively allowing all headers. This is a common CORS pattern but not obvious from the API.

The Problem

  1. The type signature shows allowedHeaders?: ReadonlyArray<string> | undefined but doesn't explain the special behavior of [] vs explicit headers
  2. Users might think an empty array means "no headers allowed" when it actually means "all headers allowed (via reflection)"
  3. There's no way to express "allow no headers" vs "allow all headers" explicitly

Suggested Documentation

Add JSDoc to clarify:

/**
 * @param options.allowedHeaders - Headers to allow in CORS requests.
 *   - If omitted or empty array: reflects back the client's `Access-Control-Request-Headers` (allows any header)
 *   - If non-empty array: only allows the specified headers
 */

Or consider adding an explicit "*" option for clarity:

allowedHeaders?: ReadonlyArray<string> | "*" | undefined

Context

I discovered this while debugging CORS issues where tracing headers (traceparent, b3, etc.) were being blocked. The fix was either:

  1. Omit allowedHeaders entirely (relies on reflection behavior)
  2. Explicitly list all needed headers

Both work, but the reflection behavior wasn't obvious from the API.


🤖 Generated with Claude Code

Metadata

Metadata

Assignees

No one assigned

    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