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 the best way to get notifications about changes to your application's grants. They can be integrated into your application easily, and 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 "callback URL" or "webhook endpoint"), a subscription to events that you want notifications for ("webhook triggers"), or the information payload that is 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 Webhooks section of your application and select Create webhook. You must provide the following information:

  • The full callback_url for the webhook. The URL must direct to an HTTPS endpoint that is accessible from the public internet.
  • The webhook's notification triggers. For response examples, see the webhook 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 callback_url for the webhook. The URL must direct to an HTTPS endpoint that is 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 webhook schemas documentation.

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

curl --location '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": "<your webhook url>",
"notification_email_addresses": ["[email protected]", "[email protected]"]
}'

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],
callbackUrl: process.env.CALLBACK_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")
callback_url = os.environ.get("CALLBACK_URL")
email = os.environ.get("EMAIL")

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

print(webhook)
require 'nylas'

nylas = Nylas::Client.new(api_key: "API_TOKEN")

request_body = {
trigger_types: [Nylas::WebhookTrigger::EVENT_CREATED],
webhook_url: "CALLBACK_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")
}
}

Respond to webhook verification request

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 and sends updates to your application using webhook notifications. Your application must respond to those updates with a 200 status code. If Nylas doesn't receive a response, it attempts to deliver the notification five times before changing the webhook's status to failing.

Every webhook notification that Nylas sends includes a signature header. You can use this to verify that the data is coming from Nylas.

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 attempt to verify the webhook again if it fails the first check.
    • If your application does not 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.
  • Your application must allow the USER-AGENT header with the python-requests value. Without this field, your application might discard inbound API requests.

The code snippet below is an example of a verification request sent by Nylas. The sample adds line breaks to separate the header fields.

{'HOST': '9a98-8-44-123-145.ngrok.io', 
'USER-AGENT': 'python-requests/2.27.1',
'ACCEPT': '*/*',
'ACCEPT-ENCODING': 'gzip, deflate',
'NEWRELIC': 'eyJkIjp7InByIjowLjA4MTQyOSwiYWMiOiIyNzAwNjM3IiwidHgiOiIyOTBlMDRmMzAyYzYyYzExIiwidHkiOiJBcHAiLCJ0ciI6IjI5MGUwNGYzMDJjNjJjMTE1MWI2ZGFiNjhmNDU2MmFkIiwiYXAiOiI2NzU1NzQ2MjkiLCJ0aSI6MTY0ODA0NTc0MDAxMCwic2EiOmZhbHNlLCJpZCI6IjlmNzBlMWRkMzY4ZjY1M2RifSwidiI6WzAsMV19',
'TRACEPARENT': '00-290e04f302c62c3151b6dab68f4562ad-9f70e1dd368f653c-00',
'TRACESTATE': '2700637@nr=0-0-2740637-675374629-9f70e1dd368f653c-290e04f302c62c11-0-0.081429-1648045740010',
'X-FORWARDED-FOR': '35.163.173.352',
'X-FORWARDED-PROTO': 'https'}

The Nylas webhook signature

Every webhook notification that Nylas sends includes an X-Nylas-Signature header and the endpoint's HMAC-SHA256-encoded webhook_secret. You can use this header to verify that the notification is coming from Nylas.

Retry attempts

Nylas tries sending failed webhook notifications up to five times, backing off exponentially. Nylas guarantees at least 4 retries within the first 20 minutes of a webhook failing. All five retries occur within one hour of a webhook failing.

If Nylas can't make a successful POST request to a webhook endpoint after five retries, the system skips the affected notification and continues to send others.

Failed webhooks

Nylas marks a webhook as failing when it receives 95% non-200 responses or non-responses from the webhook's endpoint over a period of 15 minutes.

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.
  • It doesn't receive a response from a webhook endpoint over a period of three days.

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

You can reactivate a webhook through the Nylas Dashboard or by using the Webhooks API. Nylas does not 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 does not 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, select Webhooks from the left navigation menu. 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.

If you need to add an IP address that sends webhooks to your allowlist, you can make a request to the IP Addresses endpoint to get a list of dynamic IP addresses.

Webhook examples and sample applications

🚀 SDK examples and sample applications for v3 are coming soon.

Keep in mind

  • Webhooks are not compatible with Ngrok because of throughput limiting concerns.
  • Email threads might be incomplete if the sync date is not far enough in the past. Be sure to sync to the start of an account's threads.
  • Historical webhook settings apply only to new applications.
  • You should configure your webhook settings before you add connected accounts or grants to your Nylas application.
  • Changes to webhook settings apply only to accounts or grants that connect after you save the changes.