HTTP middleware
suggest changeMiddleware is code that sits between the HTTP server and your application and sees every request and response. Logging, authentication, compression, caching headers, error pages, CORS and sessions are all usually written as middleware, so the application itself only deals with business logic.
In Ruby, server-side middleware is built on Rack. Rack is the interface between web servers (Puma, WEBrick, Falcon) and frameworks (Rails, Sinatra, Hanami, Roda). The contract is tiny:
- an application is any object that responds to
call(env)and returns[status, headers, body] envis a Hash with the request:REQUEST_METHOD,PATH_INFO,QUERY_STRING,HTTP_*headers,rack.inputand so onheadersis a Hash with lowercase header names (required since Rack 3)bodyresponds toeachand yields strings, and may respond toclose
A middleware is an application that holds another application. It gets env, can change it or answer by itself, calls the next app, and can then change the response on its way back. Since a middleware is also an app, they stack like layers of an onion.
The examples were run with Ruby 4.0, rack 3.2, rackup 2.3, webrick 1.9, Sinatra 4.2, rack-test 2.2 and Faraday 2.15:
gem install rack rackup webrick sinatra rack-test faraday
The simplest middleware
A middleware class takes the next app in initialize and implements call(env):
require 'rack'
# The application: anything that responds to call(env)
app = ->(env) { [200, { 'content-type' => 'text/plain' }, ["Hello from #{env['PATH_INFO']}\n"]] }
# A middleware: wraps another app and is itself an app
class Shout
def initialize(app)
@app = app
end
def call(env)
status, headers, body = @app.call(env)
[status, headers, body.map(&:upcase)]
end
end
wrapped = Shout.new(app)
status, headers, body = wrapped.call(Rack::MockRequest.env_for('/greet'))
p status
p headers
p body
200
{"content-type" => "text/plain"}
["HELLO FROM /GREET\n"]
Rack::MockRequest.env_for builds a valid env without a server, which is handy for experiments and tests. body.map works here only because the body is an Array. A real middleware must not assume that, as explained in the section about the response body below.
Stacking middleware with Rack::Builder
Rack::Builder is the DSL used by config.ru: use adds a middleware (with optional arguments passed to new), run sets the innermost app. The first use is the outermost layer:
require 'rack'
class Tracer
def initialize(app, name)
@app = app
@name = name
end
def call(env)
puts "#{@name}: before"
status, headers, body = @app.call(env)
puts "#{@name}: after"
[status, headers, body]
end
end
app = Rack::Builder.new do
use Tracer, 'outer'
use Tracer, 'middle'
use Tracer, 'inner'
run ->(env) { puts 'app'; [200, {}, ['ok']] }
end
Rack::MockRequest.new(app).get('/')
outer: before
middle: before
inner: before
app
inner: after
middle: after
outer: after
Order matters. A middleware sees the request after all the ones above it, and sees the response before them. For example, an error handler must be above the code whose errors it catches, and a compressor must be above anything that changes the body.
Rack::Builder creates each middleware instance once, when the stack is built. The same object then handles every request, which has consequences for thread safety (covered later in this article).
Changing the request and the response
A middleware can pass data down to the app by adding keys to env, and can add response headers on the way back. By convention, custom env keys are namespaced (app.request_id, rack.session, warden):
require 'rack'
require 'securerandom'
# Adds data to the request (env) and a header to the response
class RequestId
def initialize(app)
@app = app
end
def call(env)
# reuse the id from a proxy if it looks sane, otherwise make one
id = env['HTTP_X_REQUEST_ID']
id = SecureRandom.hex(8) unless id&.match?(/\A[\w-]{1,64}\z/)
env['app.request_id'] = id
status, headers, body = @app.call(env)
headers['x-request-id'] = id
[status, headers, body]
end
end
class Timing
def initialize(app)
@app = app
end
def call(env)
start = Process.clock_gettime(Process::CLOCK_MONOTONIC)
status, headers, body = @app.call(env)
ms = (Process.clock_gettime(Process::CLOCK_MONOTONIC) - start) * 1000
headers['server-timing'] = format('app;dur=%.1f', ms)
[status, headers, body]
end
end
app = Rack::Builder.new do
use RequestId
use Timing
run lambda { |env|
sleep 0.02
[200, { 'content-type' => 'text/plain' }, ["request #{env['app.request_id']}\n"]]
}
end
client = Rack::MockRequest.new(app)
res = client.get('/')
print res.body
puts res['x-request-id'], res['server-timing']
res = client.get('/', 'HTTP_X_REQUEST_ID' => 'abc-123')
print res.body
res = client.get('/', 'HTTP_X_REQUEST_ID' => "bad\nvalue")
print res.body
request 5144ec080911d4c5
5144ec080911d4c5
app;dur=29.6
request abc-123
request acb79e48e655c6fd
Request headers appear in env as HTTP_ plus the upper-cased name with - replaced by _, so X-Request-Id becomes HTTP_X_REQUEST_ID. Incoming headers come from the client, so the middleware validates the value before trusting it. A value with a newline would otherwise end up in a response header and in logs.
Use a monotonic clock (Process::CLOCK_MONOTONIC) for durations. Time.now can jump when the system clock is adjusted.
Header names must be lowercase
Rack 3 requires lowercase header names in responses. If you write headers['X-Request-Id'], a client may end up with two versions of the same header. Rack::Lint catches the mistake, and Rack::Headers is a Hash that lowercases keys for you:
require 'rack'
app = ->(_) { [200, { 'Content-Type' => 'text/plain' }, ['hi']] }
begin
Rack::MockRequest.new(Rack::Lint.new(app)).get('/')
rescue Rack::Lint::LintError => e
puts e.message
end
# Rack::Headers normalizes names to lowercase, handy when wrapping old apps
headers = Rack::Headers.new
headers['Content-Type'] = 'text/plain'
headers['X-Request-Id'] = 'abc'
p headers.to_h, headers['content-type']
uppercase character in header name: Content-Type
{"content-type" => "text/plain", "x-request-id" => "abc"}
"text/plain"
See HTTP headers for more on reading and writing headers.
Short-circuiting: answering without calling the app
A middleware doesn't have to call the next app. Authentication, rate limiting, maintenance mode and health checks often return a response straight away. Options are passed as extra arguments to use:
require 'rack'
require 'json'
class ApiKeyAuth
def initialize(app, keys:, skip: [])
@app = app
@keys = keys
@skip = skip
end
def call(env)
req = Rack::Request.new(env)
return @app.call(env) if @skip.include?(req.path_info)
key = req.get_header('HTTP_AUTHORIZATION').to_s.delete_prefix('Bearer ')
user = @keys.find { |k, _| Rack::Utils.secure_compare(k, key) }&.last
return unauthorized unless user
env['app.user'] = user
@app.call(env)
end
private
def unauthorized
body = JSON.generate(error: 'invalid or missing API key')
[401, { 'content-type' => 'application/json',
'www-authenticate' => 'Bearer' }, [body]]
end
end
app = Rack::Builder.new do
use ApiKeyAuth, keys: { 'secret-key-1' => 'alice' }, skip: ['/health']
run ->(env) { [200, { 'content-type' => 'text/plain' }, ["hi #{env['app.user'] || 'anonymous'}\n"]] }
end
client = Rack::MockRequest.new(app)
[
['/health', {}],
['/orders', {}],
['/orders', { 'HTTP_AUTHORIZATION' => 'Bearer wrong' }],
['/orders', { 'HTTP_AUTHORIZATION' => 'Bearer secret-key-1' }]
].each do |path, env|
res = client.get(path, env)
puts "#{path} -> #{res.status} #{res.body}"
end
/health -> 200 hi anonymous
/orders -> 401 {"error":"invalid or missing API key"}
/orders -> 401 {"error":"invalid or missing API key"}
/orders -> 200 hi alice
Rack::Request is a convenience wrapper around env (path_info, params, cookies, get_header). Creating one is cheap, and it reads and writes the same env Hash.
Rack::Utils.secure_compare compares strings in constant time, so an attacker can't guess a key byte by byte by measuring response times. See Authentication for more on this and on HTTP Basic auth.
Working with the response body
The body is the part of the contract that is easiest to get wrong. It can be an Array, a File, an Enumerator or an object that streams data as it is generated. Rules for a middleware:
- iterate it only with
each, don't assumemap,joinor[] - if you consume it, call
closeon it when you are done (it may close a file or release a database connection) - if you change its length, remove or recompute
content-length - if you only need to know when the response is finished, don't buffer it: wrap it in
Rack::BodyProxy
require 'rack'
# Rewrites HTML responses; leaves everything else untouched
class EnvBanner
def initialize(app, text)
@app = app
@text = text
end
def call(env)
status, headers, body = @app.call(env)
return [status, headers, body] unless headers['content-type'].to_s.start_with?('text/html')
html = +''
body.each { |chunk| html << chunk }
body.close if body.respond_to?(:close) # always close the body you consumed
html.sub!('<body>', "<body><div class=\"banner\">#{@text}</div>")
headers.delete('content-length') # the length changed
[status, headers, [html]]
end
end
# Runs code after the body has been fully sent, without buffering it
class AfterBody
def initialize(app)
@app = app
end
def call(env)
status, headers, body = @app.call(env)
body = Rack::BodyProxy.new(body) { puts "finished #{env['PATH_INFO']}" }
[status, headers, body]
end
end
class Chunks
def each
yield "<html><body>"
yield "<p>streamed</p>"
yield "</body></html>"
end
def close = puts('Chunks#close called')
end
app = Rack::Builder.new do
use AfterBody
use EnvBanner, 'STAGING'
map('/page') { run ->(_) { [200, { 'content-type' => 'text/html', 'content-length' => '44' }, Chunks.new] } }
map('/data') { run ->(_) { [200, { 'content-type' => 'application/json' }, ['{"a":1}']] } }
end
client = Rack::MockRequest.new(app)
res = client.get('/page')
puts res.body, res['content-length'].inspect
puts client.get('/data').body
Chunks#close called
finished /page
<html><body><div class="banner">STAGING</div><p>streamed</p></body></html>
nil
finished /data
{"a":1}
Rack::BodyProxy delegates each to the wrapped body and runs the block when the server calls close, which happens after the last byte has been written. This is the right place for access logs, metrics or cleanup that must cover the whole response, including slow streaming bodies. Rack's own Rack::CommonLogger works this way.
map in Rack::Builder routes by path prefix. Each map block can have its own use lines, so a middleware can apply to only part of the app.
Turning exceptions into responses
An error-handling middleware near the top of the stack rescues exceptions from everything below and returns a proper response instead of a server's default error page:
require 'rack'
require 'json'
require 'logger'
class JsonErrors
def initialize(app, logger: Logger.new($stdout, formatter: ->(sev, _, _, msg) { "#{sev} #{msg}\n" }))
@app = app
@logger = logger
end
def call(env)
@app.call(env)
rescue KeyError, JSON::ParserError => e
respond(400, e.message)
rescue StandardError => e
@logger.error("#{e.class}: #{e.message} (#{env['REQUEST_METHOD']} #{env['PATH_INFO']})")
respond(500, 'internal server error') # don't leak details to clients
end
private
def respond(status, message)
[status, { 'content-type' => 'application/json' }, [JSON.generate(error: message)]]
end
end
app = Rack::Builder.new do
use JsonErrors
run lambda { |env|
req = Rack::Request.new(env)
case req.path_info
when '/sum'
data = JSON.parse(req.body.read)
[200, { 'content-type' => 'application/json' }, [JSON.generate(sum: data.fetch('a') + data.fetch('b'))]]
else
raise ZeroDivisionError, 'divided by 0'
end
}
end
client = Rack::MockRequest.new(app)
puts client.post('/sum', input: '{"a":1,"b":2}').body
puts client.post('/sum', input: '{"a":1}').then { "#{it.status} #{it.body}" }
puts client.post('/sum', input: 'not json').then { "#{it.status} #{it.body}" }
puts client.get('/boom').then { "#{it.status} #{it.body}" }
{"sum":3}
400 {"error":"key not found: \"b\""}
400 {"error":"unexpected token 'not' at line 1 column 1"}
ERROR ZeroDivisionError: divided by 0 (GET /boom)
500 {"error":"internal server error"}
Two limits of this pattern:
- It only catches errors raised inside
@app.call. If the body is lazy (a streaming body or an Enumerator), errors raised while the server iterates it happen after the middleware has returned. By then the status line may already be sent. - Rescue
StandardError, notException, so thatInterruptandSystemExitstill stop the server.
Log the full error on the server and send only a generic message to the client. Stack traces in responses leak file paths and library versions. For development, Rack::ShowExceptions renders a detailed HTML error page instead. See Logging for structured logs.
Middleware must be thread-safe
Puma and Falcon handle many requests at the same time on one app instance. Since Rack::Builder creates each middleware once, instance variables set in call are shared by all requests in flight:
require 'rack'
# BROKEN: one instance serves every request, so @path is shared by all threads
class BadTagger
def initialize(app) = @app = app
def call(env)
@path = env['PATH_INFO']
status, headers, body = @app.call(env)
headers['x-path'] = @path
[status, headers, body]
end
end
# Fixed: keep per-request data in local variables (or in env)
class GoodTagger
def initialize(app) = @app = app
def call(env)
path = env['PATH_INFO']
status, headers, body = @app.call(env)
headers['x-path'] = path
[status, headers, body]
end
end
slow_app = ->(env) { sleep(env['PATH_INFO'] == '/slow' ? 0.1 : 0); [200, {}, []] }
[BadTagger, GoodTagger].each do |klass|
app = klass.new(slow_app)
t1 = Thread.new { app.call(Rack::MockRequest.env_for('/slow'))[1]['x-path'] }
sleep 0.02
t2 = Thread.new { app.call(Rack::MockRequest.env_for('/fast'))[1]['x-path'] }
puts "#{klass}: /slow got #{t1.value}, /fast got #{t2.value}"
end
BadTagger: /slow got /fast, /fast got /fast
GoodTagger: /slow got /slow, /fast got /fast
Set instance variables only in initialize (configuration). Keep per-request data in local variables or in env. Shared mutable state, like a request counter or a rate-limit table, needs a Mutex or Concurrent::Map. See Locks and synchronization.
Built-in Rack middleware
The rack gem ships many ready-made middleware. A few useful ones:
| Middleware | What it does |
|---|---|
Rack::CommonLogger |
Apache-style access log line per request |
Rack::Runtime |
adds x-runtime with the time spent in the app |
Rack::Deflater |
gzip/deflate responses when the client sends Accept-Encoding |
Rack::ETag |
adds an etag computed from the body |
Rack::ConditionalGet |
returns 304 Not Modified for matching If-None-Match / If-Modified-Since |
Rack::ContentLength |
sets content-length for bodies of known size |
Rack::Static |
serves files from a directory for given URL prefixes |
Rack::MethodOverride |
treats POST with _method=DELETE as DELETE (HTML forms) |
Rack::ShowExceptions |
HTML error page with a backtrace (development only) |
Rack::Lint |
checks that the app and middleware follow the Rack spec |
Session handling (Rack::Session::Cookie) lives in the separate rack-session gem, see Sessions. For CORS use rack-cors, see CORS.
require 'rack'
require 'zlib'
require 'stringio'
log = StringIO.new
app = Rack::Builder.new do
use Rack::CommonLogger, log # Apache-style access log
use Rack::Runtime # x-runtime header
use Rack::Deflater # gzip if the client accepts it
use Rack::ConditionalGet # 304 when if-none-match matches
use Rack::ETag # etag from a digest of the body
use Rack::ContentLength # content-length for array bodies
use Rack::Lint # checks the app follows the Rack spec
run ->(_) { [200, { 'content-type' => 'text/plain' }, ['hello ' * 100]] }
end
client = Rack::MockRequest.new(app)
res = client.get('/')
etag = res['etag']
puts "plain: #{res.status} length=#{res['content-length']} etag=#{etag} runtime=#{res['x-runtime'] ? 'yes' : 'no'}"
res = client.get('/', 'HTTP_IF_NONE_MATCH' => etag)
puts "cached: #{res.status} body=#{res.body.inspect}"
res = client.get('/', 'HTTP_ACCEPT_ENCODING' => 'gzip')
text = Zlib::GzipReader.new(StringIO.new(res.body)).read
puts "gzipped: #{res.status} #{res['content-encoding']} #{res.body.bytesize} bytes -> #{text.bytesize} bytes"
puts log.string.lines.first.sub(/\[.*?\]/, '[...]')
plain: 200 length=600 etag=W/"7e1509a85349fd10ee7e0e647f4d539a" runtime=yes
cached: 304 body=""
gzipped: 200 gzip 39 bytes -> 600 bytes
- - - [...] "GET / HTTP/1.1" 200 600 0.0002
The order follows the onion rule. ETag must be below ConditionalGet, because ConditionalGet compares the etag that ETag added. Deflater must be above both, so the ETag is computed from the uncompressed body and stays the same for gzip and plain clients.
Running a middleware stack with rackup
In a real project the stack lives in config.ru, which is evaluated inside a Rack::Builder:
# config.ru
require 'securerandom'
class RequestId
def initialize(app) = @app = app
def call(env)
env['app.request_id'] = id = SecureRandom.hex(4)
status, headers, body = @app.call(env)
headers['x-request-id'] = id
[status, headers, body]
end
end
use Rack::ContentLength
use RequestId
map '/health' do
run ->(_) { [200, { 'content-type' => 'text/plain' }, ["ok\n"]] }
end
run ->(env) { [200, { 'content-type' => 'text/plain' }, ["request #{env['app.request_id']}\n"]] }
Start it with the rackup command (from the rackup gem) and try it with curl:
$ rackup -s webrick -p 9292 -E deployment
$ curl -si localhost:9292/hello
HTTP/1.1 200 OK
Content-Type: text/plain
X-Request-Id: 7ac059ee
Content-Length: 17
Server: WEBrick/1.9.2 (Ruby/4.0.7/2026-09-15)
Date: Sat, 17 Oct 2026 19:32:05 GMT
Connection: Keep-Alive
request 7ac059ee
$ curl -s localhost:9292/health
ok
WEBrick capitalizes header names when writing them. HTTP header names are case-insensitive, and HTTP/2 servers send them lowercase.
rackup adds its own middleware depending on -E. development (the default) adds Rack::ContentLength, Rack::CommonLogger, Rack::ShowExceptions, Rack::Lint and Rack::TempfileReaper. deployment leaves out ShowExceptions and Lint. With Puma, run puma config.ru instead. It reads the same file.
Middleware in Sinatra and other frameworks
Frameworks built on Rack accept the same middleware. In Sinatra, use inside the app class adds a Rack middleware around the app. Sinatra's before/after filters are different: they run inside the app, after routing has started, and have access to Sinatra helpers.
require 'sinatra/base'
require 'rack/test'
class PoweredBy
def initialize(app, name) = (@app, @name = app, name)
def call(env)
status, headers, body = @app.call(env)
headers['x-powered-by'] = @name
[status, headers, body]
end
end
class Api < Sinatra::Base
set :host_authorization, permitted_hosts: [] # allow any Host (tests use example.org)
use PoweredBy, 'coffee' # Rack middleware, wraps the whole app
before { headers 'x-api-version' => '2' } # Sinatra filter, runs inside the app
get('/hello') { "hello\n" }
end
include Rack::Test::Methods
def app = Api
get '/hello'
puts last_response.status, last_response.headers.slice('x-powered-by', 'x-api-version'), last_response.body
get '/missing'
puts last_response.status, last_response.headers.slice('x-powered-by', 'x-api-version')
p Api.middleware.map(&:first)
200
{"x-powered-by" => "coffee", "x-api-version" => "2"}
hello
404
{"x-powered-by" => "coffee", "x-api-version" => "2"}
[PoweredBy]
Sinatra 4.1+ rejects requests with unknown Host headers in development (DNS rebinding protection), which is why the example sets host_authorization. In Rails, add middleware with config.middleware.use PoweredBy, 'coffee' (or insert_before/insert_after) and list the stack with bin/rails middleware. In Hanami, use config.middleware.use in config/app.rb.
A Sinatra app is itself a Rack middleware. If a route doesn't match, it passes the request to the next app, so you can put several small Sinatra apps in front of each other.
Testing middleware
Test a middleware on its own by wrapping a tiny fake app. rack-test gives you get, post, header and last_response. Wrapping both sides in Rack::Lint checks that the middleware passes a valid env down and returns a valid response:
require 'minitest/autorun'
require 'rack/test'
require 'rack/lint'
require_relative 'api_key_auth' # the ApiKeyAuth class from above
class ApiKeyAuthTest < Minitest::Test
include Rack::Test::Methods
def app
inner = ->(env) { [200, { 'content-type' => 'text/plain' }, ["user=#{env['app.user']}"]] }
# Lint on both sides checks the middleware gets and returns valid Rack values
Rack::Lint.new(ApiKeyAuth.new(Rack::Lint.new(inner), keys: { 'k1' => 'alice' }, skip: ['/health']))
end
def test_rejects_missing_key
get '/orders'
assert_equal 401, last_response.status
assert_equal 'Bearer', last_response['www-authenticate']
end
def test_passes_user_to_app
header 'Authorization', 'Bearer k1'
get '/orders'
assert_equal 200, last_response.status
assert_equal 'user=alice', last_response.body
end
def test_skipped_path
get '/health'
assert last_response.ok?
end
end
Run options: --seed 43027
# Running:
...
Finished in 0.024115s, 124.4049 runs/s, 207.3415 assertions/s.
3 runs, 5 assertions, 0 failures, 0 errors, 0 skips
Client-side middleware with Faraday
The same idea works for outgoing requests. Faraday, the most popular Ruby HTTP client library, builds every connection from a middleware stack that ends in an adapter (Net::HTTP by default). Request middleware modify the request on the way out, response middleware process the response on the way back. A custom middleware subclasses Faraday::Middleware and overrides on_request, on_complete and on_error:
require 'faraday'
# Client-side middleware: same onion idea, but around an outgoing request
class UserAgentAndTiming < Faraday::Middleware
def initialize(app, agent: 'my-client/1.0')
super(app)
@agent = agent
end
def on_request(env)
env.request_headers['User-Agent'] = @agent
env[:started] = Process.clock_gettime(Process::CLOCK_MONOTONIC)
end
def on_complete(env)
ms = (Process.clock_gettime(Process::CLOCK_MONOTONIC) - env[:started]) * 1000
puts format('%s %s -> %d (%.1f ms)', env.method.upcase, env.url.path, env.status, ms)
end
# called instead of on_complete when an inner middleware raises
def on_error(error)
puts "request failed: #{error.class}"
end
end
stubs = Faraday::Adapter::Test::Stubs.new do |s|
s.get('/users/1') { |env| [200, { 'content-type' => 'application/json' }, %({"id":1,"agent":"#{env.request_headers['User-Agent']}"})] }
s.post('/users') { |env| [201, { 'content-type' => 'application/json' }, env.body] }
s.get('/users/2') { [404, { 'content-type' => 'application/json' }, '{"error":"not found"}'] }
end
conn = Faraday.new(url: 'https://api.example.com') do |f|
f.request :json # encode Hash bodies as JSON
f.use UserAgentAndTiming, agent: 'books-demo/2.0'
f.response :raise_error # 4xx/5xx raise Faraday::Error subclasses
f.response :json # parse JSON response bodies
f.adapter :test, stubs # use f.adapter :net_http (the default) for real requests
end
p conn.get('/users/1').body
p conn.post('/users', { name: 'Ann' }).body
begin
conn.get('/users/2')
rescue Faraday::ResourceNotFound => e
puts "#{e.class}: #{e.response[:body]}"
end
GET /users/1 -> 200 (0.4 ms)
{"id" => 1, "agent" => "books-demo/2.0"}
POST /users -> 201 (0.1 ms)
{"name" => "Ann"}
request failed: Faraday::ResourceNotFound
Faraday::ResourceNotFound: {"error" => "not found"}
The order rules are the same as in Rack. response :json sits below raise_error, so the error body is already parsed when the exception is raised. Our timing middleware sits above raise_error, so for the 404 it gets on_error instead of on_complete. Retries (faraday-retry), cookies (faraday-cookie_jar) and logging (f.response :logger) are added the same way. The test adapter lets you test client code without a network. For more on calling APIs see REST APIs.
Tips
- Keep each middleware small and focused on one job. They are easy to reorder, reuse and test that way.
- Put error handling and request IDs near the top, compression above anything that changes the body, and authentication above the routes it protects.
- Never store per-request data in instance variables. Use locals or
env. - Don't buffer bodies you don't need to change. Use
Rack::BodyProxyfor work after the response is sent, and alwaysclosea body you consumed. - Return lowercase header names and run
Rack::Lintin development and tests. - Before writing your own middleware, check
rack,rack-contrib,rack-attack(rate limiting) andrack-cors.