Mastering Middleware In Rails: Enhance Your App's Request Lifecycle

coderyash

Yash Pandey

Posted on November 30, 2024

Mastering Middleware In Rails: Enhance Your App's Request Lifecycle

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

  1. 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
  2. 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
Enter fullscreen mode Exit fullscreen mode

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')
Enter fullscreen mode Exit fullscreen mode

We need to register the middleware in the middleware stack

config.middleware.use CustomMiddleware
Enter fullscreen mode Exit fullscreen mode

We can verify that our middleware is loaded by running:

rails middleware
Enter fullscreen mode Exit fullscreen mode

Whenever we add or modify the rails middleware, we need to restart the rails server for the changes to take effect.

rails s
Enter fullscreen mode Exit fullscreen mode

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.

💖 💪 🙅 🚩
coderyash
Yash Pandey

Posted on November 30, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related