DEV Community

Cover image for 49 Days of Ruby: Day 39 -- Middleware
Ben Greenberg
Ben Greenberg

Posted on

49 Days of Ruby: Day 39 -- Middleware

Welcome to day 39 of the 49 Days of Ruby! 🎉

Yesterday, we discussed a bit about Rack, and its critical function as the basis for our web frameworks in Ruby.

Rack also has another powerful feature, and that is its ability to create and utilize middleware.

What is middleware?

Middleware is a piece of code that sits between your application and the webserver. It intercepts the data from the server before it hits your code, and does something with it. In other words, it sits in the middle, hence middleware.

Rack, itself, comes loaded with a whole bunch of built-in middleware!

Check out some of the examples defined in the README:

  • Rack::ConditionalGet, for returning not modified responses when the response has not changed.
  • Rack::Files, for serving static files.
  • Rack::Reloader, for reloading files if they have been
  • Rack::ShowException, for catching unhandled exceptions and presenting them in a nice and helpful way with clickable backtrace.
  • Rack::ShowStatus, for using nice error pages for empty client error responses.
  • Rack::Static, for more configurable serving of static files.

From the brief descriptions offered in the list above, you can begin to get a sense of the utility that middleware provides. Whether it is serving static web pages, reloading files if they have changed, presenting error pages, catching exceptions, and a lot more, middleware can do a lot.

What does Rack middleware code look like? Let me show you an example from a real-world project.

This project is called nexmo-rack, and it verifies that the authentication signature is correct before passing on the request to your code:

if req.params['sig'] && @nexmo.signature.check(params)
  [403, {}, ['']]
Enter fullscreen mode Exit fullscreen mode

The code checks if there is a parameter called sig inside of the request from the server, which is what the signature is called. Then, it runs a method called #check from the Signature class of the code passing in the parameters as the argument. If the signature is valid then the code continues:


However, if the code is not valid then it returns an HTTP status code of 403, which means according to the Mozilla Docs:

The HTTP 403 Forbidden client error status response code indicates that the server understood the request but refuses to authorize it.

This all means that if the signature is not correct, then the request is stopped even before it reaches your actual application. Your code doesn't need to worry about validating signatures, the middleware does it for you. You can focus on what your code needs to focus on.

Go ahead and explore more middleware today and see you tomorrow!

Come back tomorrow for the next installment of 49 Days of Ruby! You can join the conversation on Twitter with the hashtag #49daysofruby.

Top comments (0)