Rack Middlewares in Ruby on Rails

What is a Middleware?

Flow diagram for Client, Server and its middleware. On the left there is the client and on the right the server. There are directional arrows indicating the sender and receiver. Each arrow is tagged with a number.
Figure 1. Basic Client-server communication diagram.

Usages

  • Routing: We can redirect a request depending on its content.
  • Performance: We can modify the request before passing it to the application to improve performance (e.g. compressing responses).
  • Logging: We can log the request stats before sending it to the client (e.g. log the response status or time to process the request).
  • Security: We can verify that the request was made by a client that we trust.
  • Profiling: (e.g. the gem rack-mini-profiler)
  • And many more!

Rack

Basic middleware example.

Writing Middleware Applications with Rack

MeasureLogs middleware code.
Example middleware call function that tracks request process time.
Figure 2: Console for the example Logger middleware.
LogRequestId middleware code.
Figure 3. Example of a request that contains X-Request-Id.

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store