Is it possible to trigger Rack middleware only on specific Rails routes?
For example, let's say I wanted to run a rate limiter middleware only on the api namespace.
namespace :api do
resources :users
end
Is it possible to trigger Rack middleware only on specific Rails routes?
For example, let's say I wanted to run a rate limiter middleware only on the api namespace.
namespace :api do
resources :users
end
I've had good success with Rack::Throttle for rate limiting. Subclass one of the built-in throttle classes and overload the
allowed?
method. Your custom logic can check which controller is being accessed and apply the rate limit as needed.You can also (now) use a Rails Engine to create an isolated set of routes that adds additional middleware to the stack for its mounted routes.
See https://stackoverflow.com/a/41515577/79079
(Unfortunately I found this question while looking to see if there was any simpler way to do it. Writing a custom middleware for every middleware that I wanted to add seems even more round-about than using a Rails::Engine)
Adding to Ian's answer, to setup up the ApiThrottle you have to:
One important thing to add is that, for me, the
path_info[:controller]
came as"api/v1/cities"
and not only as"api"
. Of course, that is due to the namespace configuration. Therefore, take care when setting up the throttler.