-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Description
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:
-
The
beforefilter does not run when a static file is served. This is explicitly tested in the Sinatra test suite:
Line 121 in cfcc70d
it 'does not run before filter when serving static files' do -
The
send_filemethod used internally bystatic!does not inject any custom headers beyond content-related defaults (e.g., content type, length). There's no hook to modify headers for static files. -
The [sinatra-cross_origin](https://github.com/britg/sinatra-cross_origin) gem does not apply to static files because it's based on middleware and route logic. Since static files are served before routes are hit, the gem has no opportunity to intervene.
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:
- A hook or setting to inject headers into static file responses.
- Middleware support for static file paths, or at least a way to apply
before/afterlogic to static files optionally. - A
static_headerssetting, similar tostatic_cache_control, where one could define headers to be applied to all static responses.