Skip to content

Static file responses don't allow setting CORS headers (e.g., Access-Control-Allow-Origin) #2088

@gerrywastaken

Description

@gerrywastaken

Sinatra currently serves static files via the static! method, which bypasses all middleware and filters (e.g., before, after). This makes it impossible to add custom headers such as Access-Control-Allow-Origin to responses for static assets in public_folder.

I've confirmed this behavior as follows:

This is a problem when serving images or fonts that need to be CORS-accessible (e.g., to be drawn onto a canvas). Without Access-Control-Allow-Origin, the browser blocks access to the data.

Workarounds

I can serve static files through explicit routes like:

get '/static/*' do |path|
  headers 'Access-Control-Allow-Origin' => '*'
  send_file File.join(settings.public_folder, path)
end

…but this defeats the point of having a fast static file path, and loses benefits like automatic static_cache_control.

Request

It would be helpful if Sinatra allowed either:

  1. A hook or setting to inject headers into static file responses.
  2. Middleware support for static file paths, or at least a way to apply before/after logic to static files optionally.
  3. A static_headers setting, similar to static_cache_control, where one could define headers to be applied to all static responses.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions