Search code examples
ruby-on-railsrubymiddlewarerack-middleware

Rack middleware - what header is added?


In my Rails 7 app I want to implement Idempotency for incoming requests. I reckon this is a good example to use Rack middleware for such an action. So the implementation is simple:

  class IdempotencyMiddleware
    def initialize(app)
      @app = app
    end

    def call(env)
      if (key = env['HTTP_CE_IDEMPOTENCYKEY']).present?
        return [200, { 'Content-Type' => 'application/json' }, ['']] if IdempotencyKey.exists?(key:)

        IdempotencyKey.create!(key:)
      end
      @app.call(env)
    end
  end

# config/initializers/idempotency_middleware.rb
Rails.application.config.middleware.use IdempotencyMiddleware

I want to check if the incoming request have ce-idempotencykey. So the question is - should I check the HTTP_CE_IDEMPOTENCYKEY or maybe just ce-idempotencykey ? I can't find anything relevant that explain me which way to go.


Solution

  • On the level of a Rack middleware, environment variables are still untranslated. Please see the Rack specification especially the section about HTTP_ Variables.

    That means it is absolute correct to use uppercase character, underscore separated key names for environment variables in Rack middlewares.