BlogSlack WebhooksRuby on Rails

How to Receive Slack Webhooks in Ruby on Rails

Skip CSRF + read request.raw_post for HMAC-friendly handlers

Rails remains the canonical Ruby web framework for SaaS. Its built-in CSRF protection is great for forms but actively blocks webhook handlers — you have to disable it on the webhook route AND read request.raw_post to get the unparsed bytes that HMAC verification needs. This guide walks through the Ruby on Rails setup for Slack webhooks end to end: capturing the raw body, verifying the signature, handling retries idempotently, and iterating locally without redeploying. Cross-reference the Slack Webhooks overview for the event catalog and sample payload.

Slack Official Webhook Docs

1. Set Up the Ruby on Rails Endpoint

The endpoint needs to do three things, in this order: read the raw body, verify the signature against those exact bytes, and only then parse the JSON for your business logic.

# config/routes.rb
Rails.application.routes.draw do
  post '/webhooks/:service', to: 'webhooks#receive', as: :webhook
end

# app/controllers/webhooks_controller.rb
class WebhooksController < ApplicationController
  # CSRF tokens don't apply to programmatic webhook deliveries.
  skip_before_action :verify_authenticity_token

  def receive
    raw_body = request.raw_post  # raw bytes — NOT parsed by Rails
    signature = request.headers['X-Signature-Header']

    # 1. Verify HMAC over raw_body
    # 2. Parse JSON only after verification passes
    # 3. Process the event idempotently (use the event id as your key)

    event = JSON.parse(raw_body)
    Rails.logger.info "Verified webhook: #{event['type'] || event}"

    head :ok
  end
end
Raw body, every time
Don't reach for params or strong-parameters on a webhook route — Rails parses JSON automatically and the byte-level body is gone. Always start with request.raw_post (or request.body.read with rewind), verify the signature, and only then JSON.parse. ActionController::Parameters and request.body are different worlds — the verifier needs the latter.

2. Verify the Slack Signature

Signing details
Algorithm
HMAC-SHA256
Header
X-Slack-Signature
Encoding
hex
Prefix
v0=

Slack signs the string `v0:{X-Slack-Request-Timestamp}:{raw_request_body}`. You must read both the timestamp and signature headers.

Ruby verification

class WebhooksController < ApplicationController
  skip_before_action :verify_authenticity_token, only: [:slack]

  def slack
    body = request.raw_post
    timestamp = request.headers['X-Slack-Request-Timestamp'].to_i
    signature = request.headers['X-Slack-Signature'].to_s

    # Reject requests older than 5 minutes (replay protection).
    return head :unauthorized if (Time.now.to_i - timestamp).abs > 300

    base = "v0:#{timestamp}:#{body}"
    expected = 'v0=' + OpenSSL::HMAC.hexdigest(
      'sha256',
      ENV['SLACK_SIGNING_SECRET'],
      base,
    )
    unless ActiveSupport::SecurityUtils.secure_compare(signature, expected)
      return head :unauthorized
    end
    render json: { ok: true }
  end
end

Wire this verification call into the Ruby on Rails handler from section 1. The pattern is identical across Ruby on Rails versions: read raw body, verify, parse JSON, dispatch.

Watch out: The 5-minute timestamp window is critical — without it, an attacker who replays a captured request can pass signature verification indefinitely. Slack's docs say to reject anything outside ±5 minutes.

See Slack's official signing docs for the canonical reference, or the cross-service signature verification guide for the same pattern in Ruby and other languages.

3. Make the Handler Idempotent

Slack can — and will — send the same event twice. Network blips, your server returning a 5xx mid-processing, deploy windows: any of these triggers a retry, and your handler will see the same event id again. Build for that on day one rather than chasing duplicate-charge bugs in production.

The simplest pattern is a unique constraint on the event id in your database. The handler does the work inside a transaction, and the insert into the events table is the last step — if a retry arrives, the unique-constraint violation tells you the event already committed and you can return 200 without re-running the side effects.

Pattern in any framework:

  1. Read raw body, verify signature.
  2. Begin transaction.
  3. Apply business logic (charge, fulfil, notify, etc.).
  4. Insert event id into processed_events with a unique constraint.
  5. Commit. Return 200.
  6. On unique-constraint violation, return 200 — the event was already processed by a prior delivery.

4. Slack Retry Behaviour

Retry policy
Max attempts
3
Total window
~36 minutes total
Backoff
1 min, 5 min, 30 min
Retries on
Non-2xx responses, timeouts (3s for slash commands)
Stops on
Any 2xx response within 3s

Combine the retry numbers above with the idempotency pattern in section 3: aim to acknowledge fast (return 200 under the timeout) and let the idempotency table absorb any duplicates from in-flight retries. The full pattern, including dead-letter queues and replay-from-capture, lives in the Webhook Retry Strategies guide.

5. Test Locally Without Deploying

The fastest iteration loop for any webhook handler is: capture a real Slack event with HookRay, then replay that captured request against your local Ruby on Rails server until the verification + business logic both pass. No need to retrigger the event in Slack, no need to redeploy.

  1. Get a free webhook URL at hookray.com — no signup.
  2. Paste the URL into your Slackdashboard's webhook settings.
  3. Trigger a test event. HookRay shows the headers, raw body, and parsed payload in real time.
  4. Use HookRay's replay feature to send the captured request against http://localhost:3000/api/webhooks/slack (or wherever your Ruby on Rails app is listening) — iterate on your code without re-poking the Slack dashboard.

Deploying the Ruby on Rails Handler

Rails apps run well on long-running containers (Render, Fly.io, Heroku, Kamal-deployed VPS). Avoid hosting Rails as serverless functions for webhook endpoints — boot time is unforgiving and Rails warm-up easily blows past the 5-15 second window most webhook senders give you before retrying.

Need a host that boots quickly enough to absorb webhook bursts? DigitalOcean droplets stay warm, support raw-body proxies cleanly, and avoid the cold-start traps of some serverless runtimes.

Capture a real Slack webhook in 30 seconds

Free webhook URL, real-time payload inspection, one-click replay. No signup required.

Start Testing — Free