DocumentationTransform a webhook payload and headers before forwarding

Transform a webhook payload and headers before forwarding

Change a webhook’s JSON body and HTTP headers before forwarding it to a private API. Test an order event in the function editor, then deliver it over a relay agent.

To change a webhook’s JSON body and headers before forwarding it, attach a request function to its output. The function reads the provider’s event and builds the HTTP request your API expects. For a private API, a relay agent inside your network delivers that request over its outbound connection.

Transform an order webhook for a private API

An order service sends a nested object with the total in cents. The billing API expects a flat JSON document and an X-Order-Schema header to select its parser. Use this sample event to try the entire mapping:

{"event":"order.paid","order":{"id":"o_1","total_cents":4990}}

1. Create the output function

Open Functions in Webhook Relay. Verify your account email if prompted. Choose Create Function, select JavaScript or Lua, then Scratch and Create. In the Code tab, replace the template with the matching example below and select Save. Copy the function name shown at the top of the editor for step 3.

const event = JSON.parse(r.body)

r.setBody(JSON.stringify({
  type: event.event,
  orderId: event.order.id,
  amount: event.order.total_cents / 100,
}))
r.setHeader("Content-Type", "application/json")
r.setHeader("X-Order-Schema", "v1")
local json = require("json")
local event, err = json.decode(r.RequestBody)
if err then error(err) end

local body, err = json.encode({
  type = event.event,
  orderId = event.order.id,
  amount = event.order.total_cents / 100,
})
if err then error(err) end

r:SetRequestBody(body)
r:SetRequestHeader("Content-Type", "application/json")
r:SetRequestHeader("X-Order-Schema", "v1")

2. Check the outgoing request

Open Test runs, paste the sample event into the request body and select Run. Check the two headers and the three fields below. The order of JSON keys can vary.

Content-Type: application/json
X-Order-Schema: v1

{"type":"order.paid","orderId":"o_1","amount":49.9}

3. Deliver it to your private endpoint

Use a test service that accepts POST requests. If you don’t have one running, start this receiver with Node.js in a terminal on the agent machine. It listens only on loopback and prints the path, the two headers and the body.

// Save as receiver.cjs and run: node receiver.cjs
const http = require("node:http")

http.createServer(async (req, res) => {
  const chunks = []
  for await (const chunk of req) chunks.push(chunk)
  console.log(req.method, req.url, req.headers["content-type"], req.headers["x-order-schema"])
  console.log(Buffer.concat(chunks).toString())
  res.writeHead(204).end()
}).listen(3000, "127.0.0.1")

In a second terminal, install the relay CLI and log in. Replace YOUR_FUNCTION_NAME with the name from step 1. Use a fresh test bucket so the sample reaches only this receiver.

relay forward --bucket order-transform-demo --function YOUR_FUNCTION_NAME http://127.0.0.1:3000/orders

Leave the agent running. It prints a public input URL for the bucket. In a third terminal, replace YOUR_INPUT_URL with that URL and send the sample:

curl -H 'Content-Type: application/json' \
  --data '{"event":"order.paid","order":{"id":"o_1","total_cents":4990}}' \
  'YOUR_INPUT_URL'

The receiver should print POST /orders application/json v1 and the mapped JSON from step 2. If the editor test passes but nothing arrives, check the bucket’s delivery log and confirm the receiver and the agent are running on the same machine. Stop both processes with Ctrl-C when you finish.

For a signed provider event, verify the signature against the original request body before changing it. The provider’s signature covers those original bytes.

Flatten nested objects and pick fields with JMESPath

For deeply nested provider payloads, the jmespath helper library extracts values with a query instead of chained property access:

const jmespath = require("jmespath")
const event = JSON.parse(r.body)

r.setBody(JSON.stringify({
  customer: jmespath.search("data.object.customer_details.email", event),
  items: jmespath.search("data.object.lines.data[].{sku: price.product, qty: quantity}", event),
}))
r.setHeader("Content-Type", "application/json")

See helper libraries for JMESPath, CSV, XML, YAML and templating modules.

Convert to a chat message (Slack, Discord, Teams)

Chat tools accept only their own message format. Build it from the event:

const event = JSON.parse(r.body)

r.setBody(JSON.stringify({
  text: `New ${event.event}: order ${event.order.id} for ${event.order.total_cents / 100}`,
}))
r.setHeader("Content-Type", "application/json")
r.setMethod("POST")

Worked examples: Stripe webhooks to Slack, webhook to Discord, webhook to Microsoft Teams. The free message formatter generates this function from a sample payload.

Convert form data to JSON

HTML forms and some providers send application/x-www-form-urlencoded or multipart bodies. Parse them and emit JSON; see URL-encoded data and multipart form data. A worked example: Jotform to JSON.

Wrap or unwrap an envelope

Some destinations want the original event inside a wrapper, others want it unwrapped:

const event = JSON.parse(r.body)

// wrap: destination expects { source, payload }
r.setBody(JSON.stringify({ source: "stripe", payload: event }))

// unwrap: forward only the inner object
// r.setBody(JSON.stringify(event.data.object))

Frequently asked questions

How do I change the JSON body of a webhook before forwarding it?

Attach a request function to the output. In JavaScript, parse r.body, build the object your API expects, and pass its JSON string to r.setBody. Use r.setHeader to set Content-Type or add a header for that destination.

Can I map fields from one provider's format to another service's API?

Yes. That is the main use: read the fields you need from the incoming event, write them into the field names the destination expects, and drop the rest. Helper libraries provide JMESPath for deep lookups and Mustache templates for text bodies.

What happens if the webhook body is invalid JSON?

JSON.parse throws an error. An uncaught error in the output request function marks that delivery as failed and prevents the request from reaching that output. Open the function’s test panel to reproduce it with the same body.

Can one webhook be transformed differently for different destinations?

Yes. Attach a different function to each output on the bucket. The same incoming event can become a Slack message on one output, a normalised JSON document on another, and pass through untouched on a third.

Did this page help you?