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.
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:
- What is Middleware?
- Why Use Middleware?
- Create Custom Middleware
- Middleware API in Rails
- How to Modify Existing Middleware
- How to Pass Parameters to Middleware
- How to Test Middleware Classes
- Extract Logging Middleware
- Additional Resources
Sounds interesting? Let's get started.