Middleware Pipeline

Rails Middleware: (Almost) Everything You Need to Know

In this post, we'll learn almost everything about Rails middleware: what it is, why we need it, how it works, and why it's so important. We'll also learn how to create and test custom middleware in a Rails app. Finally, we'll extract logging functionality in its own middleware in a simple web app.

11 min read
💡
This is the eighth article in the series on building a web application in Ruby without using Rails. In the previous article, we added support for logging, and this one shows how to extract the logging functionality to a middleware, to keep our application free from peripheral concerns.

Most web applications have some functionality that's common for many (or even all) HTTP requests. For example, an application will authenticate the user and log the incoming HTTP request, add new headers, or check if the request is for a static file and serve it from a CDN without hitting the app server.

Middleware is an elegant way to organize this common functionality, instead of spreading it everywhere in your application code, which should focus on the logic of your application. In its essence, middleware is a self-contained application that operates on a request independently before or after your main application.

As we learned in the The Definitive Guide to Rack for Rails Developers, the Rack protocol provides a simple interface for web applications and web servers to talk to each other. This communication happens through the middleware pipeline.

The Definitive Guide to Rack for Rails Developers
The word Rack actually refers to two things: a protocol and a gem. This article explains pretty much everything you need to know about Rack as a Rails developer. We will start by understanding the problem Rack solves and move to more advanced concepts like middleware and the Rack DSL.

In this post, we're going to do a deep dive into middleware; especially how and where they fit into your Rails applications. We'll learn what middleware is, why we need them, how they work, and why they're so important. I'll also show you how to create custom middleware for your Rails application and how to test it.

Finally, we'll pick up where we left off in the ruby-no-rails series and extract the logging functionality to a separate middleware.

What You'll Learn:

Sounds interesting? Let's get started.