Navigation

Create an Incoming Webhook

On this page

Overview

Some external services allow you to create incoming webhooks that external clients can call over HTTP. You can create webhooks for these services from the Stitch UI or by importing a service configuration directory that contains a webhook configuration. Select the tab below that corresponds to the method you want to use.

Procedure

1

Set Up a New Webhook

Incoming webhooks are scoped to individual services. You can create and manage a webhook from its associated service page in the Stitch UI.

To create an incoming webhook:

  1. Click Services in the left-hand navigation.
  2. Click the Service for which you want to add an incoming webhook.
  3. Select the Incoming Webhooks tab for the service.
  4. Click Add Incoming Webhook. Stitch will redirect you to the Settings screen for the new webhook.
2

Name the New Webhook

Enter a unique, identifying name for the webhook in the Webhook Name field. This name must be distinct from any other webhooks that you’ve created for the service.

3

Configure the Webhook Response

You can send a configurable HTTP Response to external services that call the webhook.

If you enable Respond With Result, the webhook will respond to incoming requests with a basic HTTP 200 response that includes the webhook function return value as its body field. You can configure a custom HTTP response from within the webhook function using the response object that Stitch automatically passes as the second argument.

4

Select a User to Execute the Webhook

Requests sent to an incoming webhook don’t necessarily come from authenticated client applications, so Stitch executes each request in the context of an existing application user. You must specify this user in the Run Webhook As option.

There are three ways to configure the execution user:

  • System: The execution user is a system user that bypasses all rules and has no user context.
  • User Id: You select a specific application user to execute the function.
  • Script: You define a function that returns the id of the execution user.
5

Specify the Request Validation Method

To validate that a webhook request is coming from a trusted source, some external services require that incoming requests incorporate a secret string in one of several prescribed manners. Other services, like the HTTP service, allow you to optionally require request validation.

If your webhook requires request validation:

  1. Select the request validation method.
  2. Enter a Secret string to use in the request validation process.
6

Write the Webhook Function

Once you’ve configured the webhook, all that’s left is to write the function that executes when someone calls the webhook. Stitch automatically passes two objects as the webhook function’s arguments:

Argument Description
payload An EJSON representation of the incoming request payload. The contents of the payload document will vary depending on the service and event that caused a webhook to fire. For a description of the payload object for a specific service, see that service’s reference page.
response An HTTP response object that configures Stitch’s response to the client that called the webhook. The object has methods that allow you to set the response’s headers, body, and status code. Calling any of these methods overrides the default response behavior.

You can use the following webhook function as a base for your own webhook:

exports = async function(payload, response) {
  // Convert the webhook body from BSON to an EJSON object
  const body = EJSON.parse(payload.body.text());

  // Execute application logic, such as working with MongoDB
  if(body.someField) {
    const mdb = context.services.get('mongodb-atlas');
    const requests = mdb.db("demo").collection("requests")
    const { insertedId } = await requests.insertOne({ someField: body.someField });
    // Respond with an affirmative result
    response.setStatusCode(200)
    response.setBody(`Successfully saved "someField" with _id: ${insertedId}.`);
  } else {
    // Respond with a malformed request error
    response.setStatusCode(400)
    response.setBody(`Could not find "someField" in the webhook request body.`);
  }
  // This return value does nothing because we already modified the response object.
  // If you do not modify the response object and you enable *Respond with Result*,
  // Stitch will include this return value as the response body.
  return { msg: "finished!" };
}

Note

If you want to debug a webhook function response from the function editor, you must manually provide the HTTP response object when you run the function.

exports(
  { body: "This document is the webhook payload" },
  new HTTPResponse()
)
7

Save the Webhook

You must save changes to your webhook before they take effect. To do so, click Save from either the Settings screen or the Function Editor.

1

Export Your Stitch Application

To create new incoming webhook with stitch-cli, you need a previously created application configuration.

You can export your application configuration from the Export tab of the Settings page in the Stitch UI, or by running the following command from an authenticated instance of stitch-cli:

stitch-cli export --app-id=<App ID>
2

Add a Webhook Configuration Directory

Create a new subdirectory in the /<service>/incoming_webhooks folder of the application directory that you exported, where <service> is the service that you want to add a webhook to. The name of the subdirectory should match the configured name of the webhook.

mkdir -p services/<service>/incoming_webhooks/<webhook name>
3

Add a Webhook Configuration File

Add a file named config.json to the new webhook directory. The configuration file should have the following form:

{
  "name": <string>,
  "respond_result": <boolean>,
  "run_as_user_id": <string>,
  "run_as_user_id_script_source": <string>,
  "options": <document>,
}
Configuration Value Description

Webhook Name

name

Required. The name of the webhook.

Note

Each webhook in a particular service must have a unique name.

Respond With Result

respond_result
Required. If true, Stitch sends a response to the client that called the webhook. The response body will be the return value of the webhook function.

Run Webhook As

run_as_user_id
run_as_user_id_script_source

Optional. The id of the Stitch user that executes the webhook function when the webhook is called.

You can specify the user id directly in run_as_user_id or provide a stringified Stitch function that accepts the webhook payload and returns the user id in run_as_user_id_script_source. If you do not specify a specific user id or a function that resolves to a user id, Stitch executes the webhook function as a system user that bypasses all rules.

Options

options
Optional. A document that contains configuration values specific to the type of the service for which you are configuring a webhook. To find the configuration values for a specific service, refer to that service’s reference page.
4

Add the Webhook Function Source Code

Add a file named source.js to the new webhook directory. The file should contain a valid function that will execute when the webhook is called.

Stitch automatically passes two objects as the webhook function’s arguments:

Argument Description
payload An EJSON representation of the incoming request payload. The contents of the payload document will vary depending on the service and event that caused a webhook to fire. For a description of the payload object for a specific service, see that service’s reference page.
response An HTTP response object that configures Stitch’s response to the client that called the webhook. The object has methods that allow you to set the response’s headers, body, and status code. Calling any of these methods overrides the default response behavior.

You can use the following webhook function as a base for your own webhook:

exports = async function(payload, response) {
  // Convert the webhook body from BSON to an EJSON object
  const body = EJSON.parse(payload.body.text());

  // Execute application logic, such as working with MongoDB
  if(body.someField) {
    const mdb = context.services.get('mongodb-atlas');
    const requests = mdb.db("demo").collection("requests")
    const { insertedId } = await requests.insertOne({ someField: body.someField });
    // Respond with an affirmative result
    response.setStatusCode(200)
    response.setBody(`Successfully saved "someField" with _id: ${insertedId}.`);
  } else {
    // Respond with a malformed request error
    response.setStatusCode(400)
    response.setBody(`Could not find "someField" in the webhook request body.`);
  }
  // This return value does nothing because we already modified the response object.
  // If you do not modify the response object and you enable *Respond with Result*,
  // Stitch will include this return value as the response body.
  return { msg: "finished!" };
}
5

Import the Webhook

Once you have added the appropriate configuration files to the webhook subdirectory, you can import the webhook into your application.

Navigate to the root of the application directory and run the following command:

stitch-cli import