1

I'm trying to set a flash[:error] to give feedback to the user. I haven't been able to find info on how to implement. One workaround I'm doing is to redirect with query params and pick that up in the controller, but it's brittle and I'm getting some errors, turbolinks sometimes makes the message render twice.

  # rack_attack.rb
  Rack::Attack.throttled_response = lambda do |env|

    headers = {
      'Location'=> "/pages/home?error=#{throttle_type}"
    }
    [301, headers, []]
  end

What's the best way to set a flash message when a user is throttled?

Ashbury
  • 2,160
  • 3
  • 27
  • 52
  • This seems reasonable to me. A cookie or DB record could be alternative solutions. I wonder though if your double flash issue is how you are handling it in the controller. Flash messages set like `flash[:error] =` are typically meant to show up after the next redirect, so you might be seeing it twice because of that. You can use `flash.now[:error] =` so that it only renders once, and not after any redirect. – Unixmonkey Mar 23 '22 at 20:55
  • In order to set a flash message you would have to put Rack::Attack pretty far down in the middleware stack so that its loaded after the cookies, sessions and flash middleware. You would have to use ActionDispatch::Flash::RequestMethods to manipulate the flash hash. To me it seems like a better question is - "Should I be using the flash to notify the user that they have been throttled?". – max Mar 24 '22 at 15:57
  • I would instead just create a controller that renders a simple "You have been throttled" message and responds with a 429 Too Many Requests. Since Rails controllers are Rack compliant you can use them to create the response here. – max Mar 24 '22 at 16:05

0 Answers0