This content has been automatically translated from Ukrainian.
Middleware in Ruby on Rails is an intermediary layer between the client request and the web application. It receives the request before it reaches the controller and can modify or process it. Similarly, Middleware can intercept the response from the application before it is sent to the client.
Rails is built on top of the Rack library, which defines a standard for such middleware layers. Middleware in this context is a regular Ruby class that implements the call(env) method. The env parameter contains all the information about the HTTP request (for example, path, headers, method). The method must return an array of three elements: response status, headers, and body.
The simplest example of custom Middleware might look like this:
class RequestLogger
def initialize(app)
@app = app
end
def call(env)
puts "Received request to #{env['PATH_INFO']}"
status, headers, body = @app.call(env)
puts "Returned status #{status}"
[status, headers, body]
end
end
In this example, each request will be logged to the console - both upon arrival and after processing.
Middleware is often used for tasks such as:
- logging requests and responses;
- caching;
- error handling;
- authentication or token verification;
- compression or modification of the response body;
- setting common headers.
In Rails, the middleware chain is defined in the config/application.rb file or can be viewed with the command:
bin/rails middleware
To add custom middleware, it can be inserted into the stack:
config.middleware.use RequestLogger
or between other layers:
config.middleware.insert_before Rack::Runtime, RequestLogger
Middleware helps isolate technical aspects of request processing - logic that is not directly related to business code. This makes the application cleaner, more extensible, and easier to maintain.
This post doesn't have any additions from the author yet.