Yash Pandey
Posted on November 30, 2024
Middleware acts as a layer between the client and server. It processes requests before they reach the controller and modifies the response when it is sent back to the client.
Middleware Lifecycle
-
Request Phase: Middlewares can intercept, modify, or reject the HTTP method before it reaches the rails routes and controllers.
Examples:- Authenticate checks
- Logging request details
- Rate Limiting
- Data Transformation
-
Response Phase: Middleware can also intercept or modify the response before it is returned to the client.
Examples:- Adding security headers
- compressing the response
- caching the response
Create the custom middleware class
We can create the custom middlewares inside the lib
directory of our rails controller, if it doesn't exist, create the lib
directory.
# lib/custom_middleware.rb
class CustomMiddleware
def initialize(app)
@app = app
end
def call(env)
# Logic before the request reaches the controller
puts "Incoming request path: #{env['REQUEST_PATH']}"
# Call the next middleware
status, header, response = @app.call(env)
# Logic before response reaches client
headers['X-Custom-Header'] = 'Hello from middleware'
# Return the modified response
[status, header, response]
end
end
Rails does not automatically load files in the lib
directory, so we need to ensure it is loaded in config/application.rb
config.autoload_paths << Rails.root.join('lib')
We need to register the middleware in the middleware stack
config.middleware.use CustomMiddleware
We can verify that our middleware is loaded by running:
rails middleware
Whenever we add or modify the rails middleware, we need to restart the rails server for the changes to take effect.
rails s
Conclusion:
Middleware in Rails is a set of components that process HTTP requests and responses. It provides a modular way to handle task like authentication, logging, and session management.
Posted on November 30, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.