🧱 Behind the Scenes of a Rails App: Understanding Middleware

Image

June 18, 2025

Have you ever wondered what happens to an HTTP request before it hits your Rails controller? πŸ€” Let me introduce you to a powerful but often overlooked part of Ruby on Rails: middleware.

What is Middleware?

Request
  ↓
[Middleware 1]
  ↓
[Middleware 2]
  ↓
[Rails Router / Controller / App]
  ↓
[Middleware 3]
  ↓
Response

Middleware is like a series of gates that every HTTP request must pass through before reaching your applicationβ€”and again on the way back with the response. It’s part of the Rack interface that Rails is built on.

Article content
What is Middleware?

Think of it as a customizable pipeline:

πŸ”„ Each layer can inspect, modify, redirect, or even halt the request or response.

Why Should You Care?

Middleware lets you handle cross-cutting concerns like:

  • βœ… Logging request timing
  • πŸ” Authenticating tokens (e.g., JWT)
  • 🌐 Setting CORS headers
  • 🚦 Throttling API requests
  • πŸ§ͺ Injecting test/debug behavior without touching business logic

A Simple Example: Logging Middleware

Let’s say we want to log the start and end time of each request:

# app/middleware/my_custom_logger.rb

class MyCustomLogger
  def initialize(app)
    @app = app
  end

  def call(env)
    Rails.logger.info "Request started at #{Time.now}"
    status, headers, response = @app.call(env)
    Rails.logger.info "Request finished at #{Time.now}"

end end

To activate it in your app, add this line to config/application.rb:

config.middleware.use MyCustomLogger

The Takeaway

Middleware offers a clean, modular way to extend your app’s behaviorβ€”before your controllers even come into play. Whether you’re building APIs, adding observability, or hardening security, middleware can be a powerful ally.

Have you written your own middleware or used some creative ones in production? Let’s discuss!

Article content

Leave a comment