Cloud Code Webhooks Guide

Webhooks are how parse-stack-next runs server-side trigger logic. They are the bridge between Parse Server and your Ruby code: Parse Server calls back into a Ruby Rack app on a matching trigger, and your model's ActiveModel callbacks (and any webhook blocks) run there.

This is a server-side-only concern. A pure client (or a server with no registered webhooks) runs all of its trigger logic locally in ActiveModel and nothing inside Parse Server.

Why register a webhook at all

A Parse::Object's ActiveModel callbacks run in the process that initiates the save:

  • A Ruby-initiated save (this SDK) runs before_save, after_create, etc. locally, before/after the REST call.
  • A save from a non-Ruby client — the JS/Swift SDKs, a raw REST call, or the Parse Dashboard — never touches your Ruby process. That trigger logic is simply skipped server-side.

Registering a webhook closes that gap. Once Parse Server has a beforeSave webhook for a class, it calls your Ruby app on every save from every client, and your callbacks run server-side for all of them.

The rule: your ActiveModel logic applies to non-Ruby clients only if the webhook is registered.

ActiveModel hooks vs Parse Server triggers

The SDK exposes the full ActiveModel lifecycle on every Parse::Object. Parse Server, separately, exposes a fixed set of webhook trigger types. They are not one-to-one — the SDK maps between them.

ActiveModel callbacks (Ruby side)

Callback Fires
before_validation / after_validation around local validation
before_save / after_save around every save (create and update)
before_create / after_create around the first save of a new object
before_update / after_update around saves of an existing object
before_destroy / after_destroy around delete

Parse Server webhook trigger types (server side)

Trigger className Notes
beforeSave / afterSave a class create and update
beforeDelete / afterDelete a class
beforeFind / afterFind a class
beforeLogin / afterLogin _User login-side hooks
afterLogout _Session
beforePasswordResetRequest _User
beforeSave / afterSave / beforeDelete / beforeFind / afterFind @File file triggers
beforeConnect @Connect LiveQuery connection (connection-global)
beforeSubscribe / afterEvent a class LiveQuery subscription / events

How they relate

  • beforeSave / afterSave carry the create variants. Parse Server has no beforeCreate / afterCreate trigger — it rejects them. The SDK runs your before_create / after_create callbacks inside the beforeSave / afterSave handler, gated on whether the object is new. So registering a beforeSave webhook enables both before_save and before_create; registering afterSave enables both after_save and after_create.

Asking for a create webhook fails fast with guidance:

  Post.webhook(:after_create) { … }
  # ArgumentError: There is no after_create webhook. Register `webhook :after_save`
  # instead — your after_create ActiveModel callbacks run inside the after_save
  # handler for new objects (registering after_save enables BOTH the after_save
  # and after_create callbacks).
  • Trigger order is honored. Within the save handler the SDK runs callbacks in ActiveModel order: before_save then before_create on the way in, after_create then after_save on the way out.

  • @File and @Connect are pseudo-classes. File triggers register against the @File className; the connection-global LiveQuery trigger uses @Connect. The SDK accepts both for the full register/fetch/delete lifecycle.

  • beforeFind / afterFind are result-side, not object-side. Unlike the save/delete triggers, a find payload carries no single object — beforeFind exposes the incoming query (via payload.query) and afterFind exposes the matched rows (via payload.objects). Over an HTTP webhook, afterFind can observe the rows or deny the query, but it cannot rewrite them. Parse Server passes every row a webhook returns through toJSONwithObjects, which turns any plain JSON object into {}, so returned rows would reach the client blank. The SDK therefore always replies "keep the rows" ({}, with no success key). Returning nil, true, or the unchanged payload.objects all pass the rows through. Returning a different set of rows (dropping or adding some) denies the query with an error instead, so rows a handler meant to hide are never returned. To restrict rows, constrain the query in beforeFind or with ACLs/CLPs; to block a query, call error! or return false. (In-process Parse.Cloud.afterFind cloud code is not subject to this limit.) It also adds a webhook round-trip to every matching query, so register it deliberately.

One non-obvious detail the SDK handles for you: Parse Server does not put the class name anywhere in the find payload body — the matched objects omit className and there is no top-level one. The SDK derives the class from the webhook URL path (<endpoint>/<trigger>/<className>) so your afterFind / beforeFind block routes correctly and payload.parse_class resolves. (If you build a Payload yourself in a test, pass the class as the second argument: Parse::Webhooks::Payload.new(body, "MyClass").)

Because the class is resolved from the route, declared :vector columns are stripped from afterFind payload.objects by default, exactly as they are from object/original/update on the other triggers (a vector_visibility :public class keeps them). This affects only what the handler sees. The rows the client receives are the ones Parse Server matched, unchanged by the webhook.

  • Auth triggers (beforeLogin / afterLogin / afterLogout / beforePasswordResetRequest) and LiveQuery triggers (beforeConnect / beforeSubscribe / afterEvent) are routed as first-class shapes — they are not object save/delete triggers, so none of them run ActiveModel save / create / destroy callbacks, even the login/logout/reset ones that carry a _User or _Session.

Identify them with the matching predicates — before_login?, after_login?, after_logout?, before_password_reset_request?, before_connect?, before_subscribe?, after_event? — or the category helpers auth_trigger? / live_query_trigger?. Useful accessors by shape:

| Trigger | what the payload carries | |---------|--------------------------| | beforeLogin | the user being authenticated as payload.parse_object (a _User). payload.user is nil — auth isn't complete yet. | | afterLogin | both payload.parse_object and payload.user (the now-authenticated user). | | afterLogout | the session as payload.parse_object (a _Session). | | beforePasswordResetRequest | the target user as payload.parse_object. | | beforeConnect | connection-global: no object; the caller token (if any) in payload.session_token; counts in payload.clients / payload.subscriptions. | | beforeSubscribe | shaped like beforeFind — payload.query / payload.parse_query; className comes from the route. Caller token in payload.session_token. | | afterEvent | the event type in payload.event (create / enter / update / leave / delete), plus payload.object / payload.original. |

The login footgun: during beforeLogin reach for payload.parse_object, not payload.user (which is nil). For connect/subscribe the live session token is at the top level of the payload, not nested under a user — the SDK captures it into payload.session_token (so payload.user_client / payload.user_agent work) and keeps it out of as_json and the request log.

Response contract — what you return matters only for the before* ones. Parse Server ignores the response body for all seven of these triggers (its webhook response handler resolves {} regardless). The only way a handler affects the operation is by rejecting it, and only the before* variants can be rejected (an after* trigger fires after the fact):

  Parse::Webhooks.route(:before_login, "_User") do |payload|
    error!("account suspended") if payload.parse_object.suspended?  # denies login
    # returning false also denies (mapped to the error response); anything else
    # — including the user object — succeeds as a no-op
  end

  Parse::Webhooks.route(:after_event, "Post") do |payload|
    AuditLog.record(payload.event, payload.parse_id)  # observe-only; return value ignored
  end

Note the asymmetry with before_save: Parse Server treats a {success:false} body as allow (only an {error} body rejects). So "return false to deny login" only works because the SDK converts that false into an error response for you. error!(message) is the explicit, message-carrying form.

LiveQuery delivery caveat. beforeConnect / beforeSubscribe / afterEvent fire inside the LiveQuery server. They are delivered to an HTTP webhook only in a co-located, single-process LiveQuery setup; with a separate LiveQuery server they are in-process (Parse.Cloud) only. beforeConnect in particular carries a live client handle that does not serialize over HTTP, so it is effectively in-process-only. Register them when you know your topology supports it.

Defining and registering webhooks

Parse::Webhooks.key = ENV.fetch("PARSE_WEBHOOK_KEY") # matches Parse Server's webhookKey

class Post < Parse::Object
  property :title, :string

  before_save  :normalize           # runs server-side once beforeSave is registered
  after_create :index_for_search    # runs inside the afterSave handler for new posts

  webhook :before_save do           # optional block, in addition to callbacks
    parse_object                    # return the object (or `false` to halt the save)
  end
end

Register with Parse Server (once, at deploy — requires the master key). endpoint is the public HTTPS URL where the Rack app is reachable:

Parse::Webhooks.register_functions!("https://hooks.example.com/webhooks")
Parse::Webhooks.register_triggers!("https://hooks.example.com/webhooks")

Mount the Rack app (config.ru):

require_relative "app/webhooks"
run Parse::Webhooks

See examples/webhook_server.rb for a complete, runnable setup.

Authenticating requests, and what master? means

Requests are accepted only when X-Parse-Webhook-Key matches Parse::Webhooks.key (PARSE_SERVER_WEBHOOK_KEY). With no key configured the Rack app refuses every request unless you opt in with Parse::Webhooks.allow_unauthenticated = true (or PARSE_WEBHOOK_ALLOW_UNAUTHENTICATED=true), which is meant for local development and tests. A signing secret does not replace the key: with no key configured, a signed request is still refused unless allow_unauthenticated is on. When both are configured, the key must match and the signature must verify.

payload.master? is true only when the body says the master key was used (a JSON true; Parse Server never sends a string) AND the request was authenticated: the webhook key matched, or a configured signature (PARSE_WEBHOOK_SIGNING_SECRET) verified. On unauthenticated ingress any caller can put "master": true in the body, so master? returns false there. Master-only field guards, ACL owner resolution, and handler checks built on master? therefore treat such a request as a normal client request. The Ruby-initiated callback dedup uses master? too, so a forged _RB_ request id plus "master": true cannot make a request skip model callbacks (including a before_save that would reject it). payload.claimed_master? returns the body's raw claim and payload.authenticated? reports whether the request was authenticated; both are for diagnostics only.

The trade-off: on unauthenticated ingress, a save made by the SDK itself is not recognized as Ruby-initiated, so its model callbacks can run twice (once in process, once through the webhook). Configure a webhook key or a signing secret to keep the dedup.

Auditing trigger coverage

The wiring above has three independent moving parts, and a callback runs server-side only when all three line up:

  1. the model's ActiveModel callback (after_save :send_email),
  2. a local webhook route so the router has a handler to run (the webhook :after_save block, or Parse::Webhooks.route(:after_save, "Post")),
  3. the server trigger registered with Parse Server (register_triggers!), so Parse Server actually POSTs to your app.

Declaring the callback alone does nothing for a non-Ruby client — the save never touches your Ruby process. It is easy for these three to drift: a new after_save callback with no block, a webhook block you never registered, or a stale server trigger pointing at a class whose block was removed.

Parse::Webhooks.trigger_audit cross-references all three across every registered class and reports the gaps. The server comparison reads the master-key-only hooks/triggers endpoint, so it needs a master-key client; pass network: false to audit callbacks against local routes only.

puts Parse::Webhooks.trigger_audit(pretty: true)        # human-readable summary
report = Parse::Webhooks.trigger_audit                  # Hash report
Parse::Webhooks.trigger_audit(network: false)           # local-only, no master key

The audit emits four kinds of findings:

  • callbacks_inert — a model has callbacks mapping to a trigger (after_save / after_create → afterSave, etc.) but the local block and/or the server trigger is missing, so they never fire for non-Ruby clients. The missing: list says which piece to add. This is the headline gap.
  • route_not_registered — a local webhook :X block exists but the trigger isn't on the server, so Parse Server never calls it. Fix by running register_triggers!.
  • orphan_server_trigger — a server trigger is registered but no local block handles it; every matching operation pays a webhook round-trip that does nothing.
  • local_only_callbacks — informational: before_update / after_update and before_validation / after_validation callbacks have no Parse Server trigger that can run them (the webhook router runs only the save and create chains). They fire for Ruby-initiated saves but never for non-Ruby clients, and no registration changes that.

Wire it into CI or a deploy check to fail fast on a coverage gap:

inert = Parse::Webhooks.trigger_audit[:summary][:findings][:callbacks_inert].to_i
abort "Webhook coverage gaps detected" if inert.positive?

Returning a value from a handler

A handler block runs with self bound to the Parse::Webhooks::Payload, so inside it you can call parse_object, params, error!, etc. directly. What the handler returns decides the reply Parse Server receives:

Trigger Allow Change Reject
before_save true, nil, or an unchanged parse_object the mutated parse_object, or a Hash of field overrides false or error!
before_delete anything else n/a false, error!, or a before_destroy callback that returns false
after_find nil, true, or the unchanged payload.objects not possible over HTTP (see above) false or error!
function the return value is the function result error!

How a before_save change reaches Parse Server: Parse Server replaces the pending write with the object a beforeSave webhook returns. The SDK therefore never replies with only your changes. When nothing changed, it replies "keep the write as sent", so the client's atomic operators (Increment, Add, Remove, Delete, relation operators) and any undeclared fields reach the database untouched. When the handler changed fields, the reply is the client's full write with your changes layered on top: operators on fields you did not touch are passed through as operators, fields the model does not declare (and _User signup fields such as password and authData) are kept, and a field you set back to its stored value is dropped from the write. A field you rewrite is written as an absolute value. Edits made in place on parse_object count even if the handler returns true.

An operator on a dotted sub-key ("meta.count") arrives only as its resulting sub-document, so on an update the SDK writes back just the sub-keys that changed, as dotted paths, and a removed sub-key as a Delete. The split is one level deep: a changed sub-key is written whole at field.sub, nested objects included, because Parse Server rebuilds the afterSave object from a dotted key only one level deep. Concurrent writes to other sub-keys of the field survive. Some limits remain:

  • Two concurrent writes inside the same sub-key can still overwrite each other, including two operators on deeper paths under it (meta.count.value and meta.count.other).
  • An array is written whole, so a concurrent Add to an array inside a sub-document is lost.
  • When a changed sub-key would carry a typed value (a Date, Bytes, Pointer, or other __type value), the whole field is written instead, because Parse Server stores a dotted typed value without converting it. Unchanged typed values and deletes do not trigger this.
  • A client that replaces a whole sub-document gets a merge: the changed sub-keys are written and the sub-keys it knew about and removed are deleted, so a sub-key another request added in the meantime survives.
  • Parse Server reports the reply's dotted keys back to the client in the save response. The JavaScript SDK applies them; other clients may need to fetch the object to see the merged value.
  • A dotted key in a Hash the handler returns ({ "meta.y" => 5 }) is folded into the parent path the reply writes whole. A key deeper than one level ("meta.count.value") is folded into a meta.count write built from the pending object, and on a create every dotted key folds into its whole field. An operator folded this way ({"__op" => "Increment"}, Add, AddUnique, Remove, Delete) is applied to the value it replaces; an operator that cannot be applied there, or two of your own keys that conflict ("meta.a" => 5 with "meta.a.b" => 6), fails the save with an error. Hash keys may use Ruby names (acl:); they are mapped to the stored field names.

On a create, returning parse_object also writes the model's declared defaults for fields the client did not send, including its ACL policy. Parse Server stores a create without an ACL as public read and write, so the reply always carries the ACL your policy resolves, exactly as an SDK-side create would. Owner-based policies (:owner_else_private, the default, as well as :owner_else_public and :owner_but_public_read) take the owner from the declared owner: field and, when that is empty, from the user who made the request, so a signed-in client owns what it creates. A request without a user gets the policy's fallback (master-key only under :owner_else_private), and so does a master-key request. A _User class declared with owner: :self is owned by the new user, never by the requester: the reply carries the policy's ACL without an owner entry and Parse Server adds the new user's own read and write. An ACL the client sent is kept, and an ACL the handler sets always wins, whether through acl= or mass assignment. A guard :acl, :master_only revert on a create returns the ACL to the class policy rather than to {}. Built-in classes such as _User that have no policy of their own keep Parse Server's defaults. A handler that returns true, nil, or a Hash keeps the client's write as sent, so a create without an ACL stays public; return parse_object to apply the policy. An ACL the handler assigns on parse_object (parse_object.acl = Parse::ACL.new) is written whatever the handler returns, unless a returned Hash sets ACL itself.

after_destroy callbacks run in the after_delete handler (once per delivery, skipped for deletes the SDK itself made, whose callbacks already ran locally). before_destroy callbacks run in before_delete when the handler returns parse_object.

error!(message, code: 137) attaches a Parse error code to the error reply and to the raised Parse::Webhooks::ResponseError#code. Parse Server's HTTP webhook adapter currently reports every webhook error to the client as code 141 (SCRIPT_FAILED), so the code is mainly useful to in-process callers such as Parse::Webhooks.run_function. Any other exception a handler raises is answered with a generic {"error": "Webhook handler failed."} reply (the exception class and a redacted message are logged), so internal details never reach the client.

A request for a function with no registered handler is answered with an error. A trigger with no registered handler passes the operation through unchanged.

You can set that value either with an explicit return or by letting it be the block's last expression — both work:

Parse::Webhooks.route :before_save, :Post do
  post = parse_object

  return post if post.title.present?   # explicit early return
  error! "title is required"           # raise to reject the save
end

# Equivalent, using the last-expression value:
Parse::Webhooks.route :before_save, :Post do
  post = parse_object
  post.title.present? ? post : error!("title is required")
end

The legacy proc idioms remain valid too — next value and break value both set the result. return, like anywhere in Ruby, ends the handler immediately, so nothing written after it in the same block runs. To run work after the response, use after_response rather than writing code after the return.

Deferring work until after the response

payload.after_response { … } (alias defer) registers a block to run after the webhook response has been sent to Parse Server — off the critical path of the save or function the client is waiting on. The handler still returns its value synchronously (that value is the response Parse Server acts on); the deferred block runs afterward. Use it for follow-up work that should not add latency: search indexing, cache warming, fan-out notifications.

Parse::Webhooks.route :after_save, :Post do
  post = parse_object
  after_response { SearchIndex.reindex(post.id) }   # runs after the reply is sent
  post
end

How it runs:

  • Under Puma or Unicorn the block is enqueued on rack.after_reply and runs once the response is flushed to the socket, on the same worker thread — so it adds nothing to the client's round-trip.
  • On a server without rack.after_reply (e.g. WEBrick) it falls back to a detached thread per request with deferred work — there is no pool or cap, so under high request volume those threads can accumulate. Run the webhook app under Puma or Unicorn in production (both provide rack.after_reply, which runs the work on the existing worker thread with no extra thread spawned); the thread fallback is best treated as a development-server convenience.
  • Multiple after_response blocks run in registration order, and each is isolated — one raising affects neither the response nor the others.
  • self inside the block is the payload, so parse_object, params, etc. are available (it closes over the handler's scope).

Things to know before relying on it:

  • Success path only. Deferred blocks run only when the handler produced a successful response. If a before_save rejects the write (error!, a raise, or returning false), its registered after_response blocks do not run.
  • "After the response" is not "after the row commits." The block runs after the response is flushed. For before_save that is before Parse Server has committed the write; even for after_save the SDK does not guarantee commit ordering relative to the deferred block. Do not rely on the persisted row being readable inside it.
  • In-process and best-effort. The work runs in the web worker and does not survive a restart, crash, or deploy. For work that must happen — payment capture, irreversible side effects — hand it to a durable job queue (Sidekiq / ActiveJob) instead; after_response is for latency-shedding, not durability.
  • Mounted-app only. Deferred blocks are drained by the Parse::Webhooks Rack app. Invoking a handler directly (Parse::Webhooks.run_function, or calling call_route in a unit test) does not run them — after_response is a no-op there.
  • Capturing user_client / user_agent extends the token's lifetime. A deferred block closes over the payload, so referencing payload.user_client / payload.user_agent (or payload.session_token) keeps the caller's live session token in memory until the block finishes — beyond the synchronous request. That is fine and expected when the deferred work needs to act as the caller; just don't capture them when the work doesn't need the user's authority (use a master-key client instead), so the token isn't pinned longer than necessary.

Latency: webhooks are synchronous

Every registered webhook adds a separate, synchronous HTTP round-trip to the client's operation. Parse Server waits for the webhook to return before proceeding — and it waits even on afterSave, despite the afterSave return value being a no-op.

This has direct design consequences for afterSave (and afterDelete):

  • Enqueue, don't execute. Treat after_save as a place to hand work to a background job, not to do long-running logic inline. Anything slow here is added latency on every save, for every client. For in-process follow-up that doesn't need a durable queue, after_response moves it off the client's round-trip; for anything that must happen, use a real job queue.
  • Avoid saving other objects during an afterSave. Each cascading save fires its own webhooks, which can fire more — a latency cascade. If you must, do it in a background job, not inline in the handler.

beforeSave is necessarily inline (it can mutate or reject the write), so keep it lean and deterministic.

Server-side dedup: two distinct mechanisms

Two different "dedup" systems protect webhook handling. They solve different problems — don't conflate them.

1. Ruby-initiated dedup (keep logic local, prevent double-runs)

When a save is initiated by this SDK with the master key, Parse Stack tags the request as trusted-Ruby-initiated (an _RB_ request-id marker plus the master key). It has already run the model's before_save / after_save / after_create ActiveModel callbacks locally. The webhook therefore does not re-run those callbacks — that would double-fire side effects (e.g. an after_save :send_email would send two emails per save).

The intent is to keep trigger logic local when possible and run it exactly once. Note that any logic in the webhook block itself still runs; only the duplicate ActiveModel callback pass is skipped. A spoofed _RB_ marker without the master key does not get this treatment, and neither does a claimed master key on an unauthenticated request (no webhook key match and no verified signature): the callbacks run in the webhook as usual. On unauthenticated ingress this means SDK-initiated saves run their callbacks twice; configure a webhook key or signing secret to keep the dedup.

2. Server-initiated replay / freshness protection (inbound)

This protects the webhook endpoint against replayed inbound POSTs — lib/parse/webhooks/replay_protection.rb:

  • Nonce-keyed dedup. When a delivery carries an X-Parse-Request-Id or X-Parse-Webhook-Nonce header, a bounded LRU records a digest of (nonce, body); a duplicate seen within replay_window_seconds is rejected with "Webhook replay detected.". Parse Server sends neither header on its own deliveries, so add one in the proxy or wrapper that delivers webhooks if you want dedup. Without a nonce the SDK does not dedup on the body alone: two legitimate identical requests (the same function called twice with the same params) cannot be told apart from a replay that way.
  • Opt-in HMAC freshness verification. Set a signing_secret and the receiver verifies two headers:
    • X-Parse-Webhook-Timestamp — Unix epoch seconds; requests outside signing_max_skew_seconds (default 300) are rejected as stale.
    • X-Parse-Webhook-Signature — hex HMAC-SHA256 of "#{timestamp}.#{body}" keyed with the signing secret.

A signed delivery is deduplicated on its signature, so a captured request cannot be replayed inside the skew window, even with an altered or missing nonce. To send identical bodies more than once in the same second, include an X-Parse-Webhook-Nonce header and sign "#{timestamp}.#{nonce}.#{body}" instead; each delivery then has its own signature, and a signature cannot be reused under another nonce.

Parse::Webhooks::ReplayProtection.signing_secret = ENV["PARSE_WEBHOOK_SIGNING_SECRET"]
Parse::Webhooks::ReplayProtection.replay_window_seconds = 120
Parse::Webhooks::ReplayProtection.signing_max_skew_seconds = 300

This is inbound protection and is unrelated to request idempotency (X-Parse-Request-Id), which dedups the SDK's own outbound retries on the Parse Server side. Different direction, different mechanism.