Version:
Only show these results:

Using webhooks with Nylas

Webhooks allow your Nylas application to receive notifications in real time when certain events occur. They use a push notification protocol to notify you of events, rather than you having to periodically request ("poll for") the latest changes from Nylas.

Because they're lightweight, webhooks are a good way to get notifications about changes to your application's grants. You can integrate them into your application easily, and they scale seamlessly as you grow.

How webhooks work

🔍 The term "webhook" can refer to any of three component parts: a location where you receive notifications (the "webhook URL" or "webhook endpoint"), a subscription to events that you want notifications for ("webhook triggers"), or the information payload that's sent when a trigger condition is met (the "webhook notification"). We try to be specific in this documentation to avoid confusion.

When you configure a webhook, you specify a URL that Nylas sends HTTP POST requests to, and subscribe it to specific event types ("webhook triggers"). When a webhook is triggered, Nylas sends information about the affected object to your application. For example, when an end user receives an email message, Nylas can make a POST request to your webhook endpoint to let you know about it. Your application can then use that data to query the Nylas API for details about the object.

A flow diagram showing how Nylas generates and sends webhooks to your application.

You can specify the events that you want to be notified about from the Nylas Dashboard, using the Webhooks API, or using the Nylas SDKs.

For more information, see the Webhooks reference documentation.

How to set up webhooks

You follow these basic steps to set up a webhook subscription:

  1. Build a webhook endpoint into your project. This is a URL that Nylas sends webhook notifications to.
  2. Make sure your project can respond to a verification request from Nylas with a 200 OK within 10 seconds.
  3. Make sure you request the correct authentication scopes for your webhook subscriptions, so Nylas can access the objects that you want to monitor.
  4. Set up your webhook subscription in the v3 Nylas Dashboard, by making an API request, or using the Nylas SDKs.
  5. Complete the verification process by returning the exact value of the challenge parameter.

Before you begin

Before you can start using webhooks, your environment must have the following prerequisites:

  • A v3 Nylas application that can respond to a verification request with a 200 OK.
  • Webhooks enabled using the Nylas Dashboard, Webhooks API, or Nylas SDKs.
  • The correct authentication scopes for your webhooks.

Create a webhook

The following sections describe how to create webhooks using the Nylas Dashboard, the Webhooks API, and the Nylas SDKs.

You can create multiple webhooks for each of your Nylas applications, but each webhook must have its own unique endpoint.

Create a webhook in the Nylas Dashboard

To create a webhook using the Nylas Dashboard, navigate to the Notifications section of your application and select Create webhook. You must include the following information:

  • The full webhook_url. The URL must direct to an HTTPS endpoint that's accessible from the public internet.
  • The webhook's notification triggers. For response examples, see the notification schemas documentation.

When you have all the information set, click Create webhook. The new webhook is displayed on the Webhooks page.

Create a webhook using the Webhooks API

To create a webhook using the Webhooks API, make a POST /v3/webhooks request with the following information:

  • The full webhook_url. The URL must direct to an HTTPS endpoint that's accessible from the public internet.
  • A list of trigger_types that you want to listen for. Nylas sends webhook notifications for the triggers that you include. For response examples, see the notification schemas documentation.

The following snippet is an example of a POST request to create a webhook.

curl --request POST \
--url 'https://api.us.nylas.com/v3/webhooks/' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer <NYLAS_API_KEY>' \
--data-raw '{
"trigger_types": [
"grant.created",
"grant.deleted",
"grant.expired"
],
"description": "local",
"webhook_url": "<WEBHOOK_URL>",
"notification_email_addresses": ["jane@example.com", "joe@example.com"]
}'

Nylas returns a webhook_secret, which you use to authenticate webhooks and verify that webhook notifications are valid.

Create a webhook using the Nylas SDKs

The following code samples show how to create a webhook using the Nylas SDKs.

import 'dotenv/config'
import Nylas from "nylas"

const NylasConfig = {
apiKey: process.env.NYLAS_API_KEY,
apiUri: process.env.NYLAS_API_URI,
}

const nylas = new Nylas(NylasConfig)

const createWebhook = async () => {
try {
const webhook = await nylas.webhooks.create({
requestBody: {
triggerTypes: [WebhookTriggers.EventCreated],
webhookUrl: process.env.WEBHOOK_URL,
description: "My first webhook",
notificationEmailAddress: process.env.EMAIL,
}
})

console.log("Webhook created:", webhook)
} catch (error) {
console.error("Error creating webhook:", error)
}
}

createWebhook()
from dotenv import load_dotenv
load_dotenv()

import os
import sys
from nylas import Client
from nylas.models.webhooks import WebhookTriggers

nylas = Client(
os.environ.get('NYLAS_API_KEY'),
os.environ.get('NYLAS_API_URI')
)

grant_id = os.environ.get("NYLAS_GRANT_ID")
webhook_url = os.environ.get("WEBHOOK_URL")

email = os.environ.get("EMAIL")

webhook = nylas.webhooks.create(
request_body={
"trigger_types": [WebhookTriggers.EVENT_CREATED],
"webhook_url": webhook_url,
"description": "My first webhook",
"notification_email_address": email,
}
)

print(webhook)
require 'nylas'

nylas = Nylas::Client.new(api_key: "<NYLAS_API_KEY>")

request_body = {
trigger_types: [Nylas::WebhookTrigger::EVENT_CREATED],
webhook_url: "<WEBHOOK_URL>",
description: 'My first webhook',
notification_email_address: ["EMAIL_ADDRESS"]
}

begin
webhooks, = nylas.webhooks.create(request_body: request_body)

puts "Webhook created: #{webhooks}"
rescue StandardError => ex
puts "Error creating webhook: #{ex}"
end
import com.nylas.NylasClient;
import com.nylas.models.*;
import com.nylas.resources.Webhooks;
import com.nylas.models.WebhookTriggers;
import java.util.*;

public class webhooks {
public static void main(String[] args) throws NylasSdkTimeoutError, NylasApiError {
NylasClient nylas = new NylasClient.Builder("<NYLAS_API_KEY>").build();

List<WebhookTriggers> triggers = new ArrayList<>();
triggers.add(WebhookTriggers.EVENT_CREATED);

CreateWebhookRequest webhookRequest = new CreateWebhookRequest(triggers, "<WEBHOOK_URL>",
"My first webhook", "<EMAIL_ADDRESS>");

try {
Response<WebhookWithSecret> webhook = new Webhooks(nylas).create(webhookRequest);

System.out.println(webhook.getData());
} catch (Exception e) {
System.out.println("Error: " + e);
}
}
}
import com.nylas.NylasClient
import com.nylas.models.*
import com.nylas.resources.Webhooks

fun main(args: Array<String>){
val nylas: NylasClient = NylasClient(apiKey = "<NYLAS_API_KEY>")
val triggersList: List<WebhookTriggers> = listOf(WebhookTriggers.EVENT_CREATED)

val webhookRequest: CreateWebhookRequest = CreateWebhookRequest(triggersList,
"<WEBHOOK_URL>",
"My first webhook",
"<EMAIL_ADDRESS>")

try {
val webhook: Response<WebhookWithSecret> = Webhooks(nylas).create(webhookRequest)

println(webhook.data)
} catch(exception : Exception) {
println("Error :$exception")
}
}

Authenticate a webhook

The first time you create a webhook or set an existing webhook's state to active, Nylas checks that it's valid by sending a GET request to its endpoint. The request includes a challenge query parameter for the verification process. Your Nylas application must return the exact value of the challenge parameter in the body of its response.

📝 If you're using a low- or no-code endpoint, you might not receive the Challenge query parameter. If this happens, contact Nylas Support for help with setting up your webhook.

After the webhook is verified, Nylas generates a webhook_secret. You can rotate it by making a Rotate Webhook Secret request.

The Challenge query parameter

When your Nylas application receives a request that includes the challenge query parameter, it's subject to the following requirements:

  • Your application has up to 10 seconds to respond to the verification request.
    • Nylas will not try to verify the webhook again if it fails the first check.
    • If your application doesn't respond to the verification request, Nylas returns a 400 BAD REQUEST error.
  • Your application must return the exact value of the challenge parameter in the body of its response. Do not include any other data — not even quotation marks.
  • Your application must not use chunked encoding for its response to Nylas' verification request.

The code snippet below is an example of a verification request sent by Nylas.

curl -X 'GET' '<WEBHOOK_URL>?challenge=bc609b38-c81f-47fb-a275-1d9bd61a968b'   

Specify fields for webhook notifications

🚀 Nylas v3 offers field selection for webhooks, so you can specify the fields you want to receive for certain webhook triggers. If you're interested in trying it out, contact Nylas Support.

Respond to webhook notifications

After you have a webhook destination set up in your application, Nylas sends it notifications about updates. Your application must respond to webhook notifications with a 200 status code to prevent Nylas marking it as failing or failed.

📝 Keep in mind: It might take up to two minutes for you to receive webhook notifications for newly authenticated grants.

Every webhook notification Nylas v3 sends includes the X-Nylas-Signature header. This header contains a hex-encoded HMAC-SHA256 signature of the request body, and uses your webhook's webhook_secret value as the signing key. The signature is for the exact content of the request body, so make sure that your processing code doesn't modify the body before checking the signature.

Failing and failed webhooks

If Nylas doesn't receive a response to a webhook notification, it attempts to deliver the notification five times, backing off exponentially. Nylas guarantees at least 4 retries within the first 15 minutes of a webhook failing, and all 5 retries within an hour. If Nylas can't successfully deliver the webhook notification after five retries, the system skips the affected notification, but continues to send others in case there is a problem that prevents your project from acknowledging the specific notification.

Nylas marks a webhook as failing when it receives 95% non-200 responses or non-responses from the destination for a specific webhook trigger over a period of 15 minutes. Nylas continues to make POST requests to the affected webhook destination over 72 hours after a webhook notification first fails, backing off exponentially.

Nylas marks a webhook as failed in the following circumstances:

  • It receives 95% non-200 responses or non-responses from a webhook endpoint over a period of three days (72 hours).
  • It doesn't receive a response from a webhook endpoint over a period of three days (72 hours).

When a webhook's state changes to either failing or failed, Nylas sends you an email notification about the change.

📝 In some cases, the email message notifying you that a webhook is failing or failed might end up in your Spam folder. Be sure to add the notification email address to your allowlist to avoid this in the future!

You can reactivate a webhook through the Nylas Dashboard or by using the Webhooks API. Nylas doesn't automatically restart or reactivate failed webhooks. Reactivated webhooks don't send notifications for events that occurred while they were marked as failed.

Activate and deactivate webhooks

By default, Nylas webhooks are set to active. When you deactivate a webhook, Nylas stops sending all events associated with it to your endpoint. When you reactivate a webhook, Nylas starts sending data from the time that it was reactivated. Nylas doesn't send notifications for events that occurred while a webhook was inactive.

Deactivate webhooks in the Nylas Dashboard

To deactivate a webhook using the Nylas Dashboard, click Notifications in the left navigation, find the webhook whose state you want to change, and set it to inactive.

Deactivate webhooks using the Webhooks API

To deactivate a webhook using the Webhooks API, make a PUT /v3/webhooks/{id} request to update the status to inactive.

Test webhooks

🔍 The Nylas APIs block requests to Ngrok testing URLs. Nylas recommends using Visual Studio Code port forwarding, the Nylas CLI, Hookdeck, or a similar webhook tool instead.

You can use the new Get Mock Payload endpoint to test your webhook destinations or receivers. When you make this request, Nylas returns a mock webhook notification payload for the specified trigger type (for example, calendar.created).

Truncated webhooks

In v3, Nylas sends webhook notifications as JSON payloads that contain the object that triggered the notification, up to a maximum payload size of 1 MB. If a webhook notification exceeds the size limit, Nylas truncates the payload by removing the body content, and adds the .truncated suffix to the webhook trigger name (for example, message.created.truncated). This reduces the size of the payload and improves performance.

When you receive a truncated webhook notification, you'll need to re-query the Nylas APIs to get the data. For example, if you receive a message.updated.truncated notification, make a Return message request that includes the message ID.

If you subscribe to a webhook trigger that can be truncated, Nylas automatically sends you .truncated notifications as well. You don't need to subscribe to webhook triggers with the .truncated suffix separately, and the suffix doesn't appear as a option in the v3 Dashboard. See the list of available trigger types for more information.

You can monitor for .truncated notifications to create automations that retrieve the full affected object. For example, you can create an automation that makes a GET /v3/grants/<NYLAS_GRANT_ID>/messages/<MESSAGE_ID> request when your application receives a message.updated.truncated notification.

Webhook examples and sample applications

Nylas maintains code samples that show how to work with webhooks. You can build from these examples, or use them as a reference point to get started on your own implementation.

The following sample repositories read webhooks using the v3 Nylas SDKs:

The Nylas DevRel team also releases blog posts periodically that walk through specific scenarios in detail.

Keep in mind

  • Webhooks are not compatible with Ngrok because of throughput limiting concerns.
  • Changes to webhook settings will apply to all grants for future sync. However, Nylas does not load any data from the past. For example, if you subscribe to the event.updated webhook trigger, you'll only receive notifications for the events updated from the moment you apply the new settings.

More resources