A middleware is nothing but a class with a
call
method that receives the incoming HTTP request (env
) from the web server, processes it before passing it to the Rails application, processes the response received from the application, and returns the response back to the web server.
When we say an application is Rack-compliant, it means the following:
It has a
call
method that accepts a single argumentenv
, containing all the data about the request, andIt returns an array containing the status, headers, and response.
Because the Rack interface is so simple, you can use any code that implements this interface in a Rack application, allowing you to build small, focused, and reusable applications that work together to provide different functionalities. These mini-components are known as Middleware.
It's best to envision middleware as a series of "layers" HTTP requests must pass through before they hit your application. Each layer can examine the request, modify it, and even reject it entirely.
Here's a simple middleware that prints some text before and after passing the request to the application (or the next middleware in the pipeline).
class CustomMiddleware
def initialize(app)
@app = app
end
def call(env)
puts 'before'
result = @app.call(env)
puts 'after'
result
end
end
Two important things to note here:
The middleware receives the application (or the next middleware) in the constructor.
After receiving the response from the application, it has to return the response to the web server, or the next middleware in the pipeline.