# Validate Webhook requests from SendGrid

> \[!WARNING]
>
> This example uses headers and cookies, which are only accessible when your Function is running `@twilio/runtime-handler` version `1.2.0` or later. Consult the [Runtime Handler guide](/docs/serverless/functions-assets/handler) to learn more about the latest version and how to update.

Protecting your Twilio Functions from non-Twilio requests is usually just a matter of setting a Function's [visibility](/docs/serverless/functions-assets/visibility) to `Protected`. However, if you'd like to create a Function that's intended to only handle incoming Webhook requests from a product such as [SendGrid](https://sendgrid.com/), validation will require some manual inspection of headers, which are now accessible!

In this example, we'll create a Function which will serve as the Event Webhook for your SendGrid account. The Function will validate if the incoming request came from SendGrid, and send a text message to a designated phone number if an email has been opened.

## Create and host a Function

In order to run any of the following examples, you will first need to create a Function into which you can paste the example code. You can create a Function using the Twilio Console or the [Serverless Toolkit](/docs/labs/serverless-toolkit) as explained below:

## Console

If you prefer a UI-driven approach, creating and deploying a Function can be done entirely using the Twilio Console and the following steps:

1. Log in to the Twilio Console and navigate to the [Functions tab](https://www.twilio.com/console/functions/overview). If you need an account, you can sign up for a free Twilio account [here](https://www.twilio.com/try-twilio)!
2. Functions are contained within **Services**. Create a **[Service](/docs/serverless/functions-assets/functions/create-service)** by clicking the **[Create Service](https://www.twilio.com/console/functions/overview/services)** button and providing a name such as *test-function*.
3. Once you've been redirected to the new Service, click the **Add +** button and select **Add Function** from the dropdown.
4. This will create a new [Protected](/docs/serverless/functions-assets/visibility) Function for you with the option to rename it. The name of the file will be path it is accessed from.
5. Copy any one of the example code snippets from this page that you want to experiment with, and paste the code into your newly created Function. You can quickly switch examples by using the dropdown menu of the code rail.
6. Click **Save** to save your Function's contents.
7. Click **Deploy All** to build and deploy the Function. After a short delay, your Function will be accessible from: `https://<service-name>-<random-characters>-<optional-domain-suffix>.twil.io/<function-path>`\
   For example: `test-function-3548.twil.io/hello-world`.

## Serverless Toolkit

The [Serverless Toolkit](/docs/labs/serverless-toolkit) enables you with local development, project deployment, and other functionality via the [Twilio CLI](/docs/twilio-cli/quickstart). To get up and running with these examples using Serverless Toolkit, follow this process:

1. From the CLI, run `twilio serverless:init <your-service-name> --empty` to bootstrap your local environment.
2. Navigate into your new project directory using `cd <your-service-name>`
3. In the `/functions` directory, create a new JavaScript file that is named respective to the purpose of the Function. For example, `sms-reply.protected.js` for a [Protected](/docs/serverless/functions-assets/visibility) Function intended to handle incoming SMS.
4. Populate the file using the code example of your choice and save. **Note** A Function can only export a single handler. You will want to create separate files if you want to run and/or deploy multiple examples at once.

Once your Function(s) code is written and saved, you can test it either by running it locally (and optionally tunneling requests to it via a tool like [ngrok](https://ngrok.com/)), or by deploying the Function and executing against the deployed url(s).

### Run your Function in local development

Run `twilio serverless:start` from your CLI to start the project locally. The Function(s) in your project will be accessible from `http://localhost:3000/sms-reply`

* If you want to test a Function as a [Twilio webhook](/docs/usage/webhooks/getting-started-twilio-webhooks), run: `twilio phone-numbers:update <your Twilio phone number> --sms-url "http://localhost:3000/sms-reply"`\
  This will automatically generate an ngrok tunnel from Twilio to your locally running Function, so you can start sending texts to it. You can apply the same process but with the `voice-url` flag instead if you want to test with [Twilio Voice](/docs/voice).
* If your code does *not* connect to Twilio Voice/Messages as a webhook, you can start your dev server and start an ngrok tunnel in the same command with the `ngrok` flag. For example: `twilio serverless:start --ngrok=""`

### Deploy your Function

To deploy your Function and have access to live url(s), run `twilio serverless:deploy` from your CLI. This will deploy your Function(s) to Twilio under a development environment by default, where they can be accessed from:

`https://<service-name>-<random-characters>-dev.twil.io/<function-path>`

For example: `https://incoming-sms-examples-3421-dev.twil.io/sms-reply`

Your Function is now ready to be invoked by HTTP requests, set as the [webhook](/docs/usage/webhooks/getting-started-twilio-webhooks) of a Twilio phone number, invoked by a Twilio Studio **[Run Function Widget](/docs/studio/widget-library/run-function)**, and more!

```js title="Validate Webhook requests from SendGrid"
const { EventWebhook, EventWebhookHeader } = require('@sendgrid/eventwebhook');

// Helper method for validating SendGrid requests
const verifyRequest = (publicKey, payload, signature, timestamp) => {
  // Initialize a new SendGrid EventWebhook to expose helpful request
  // validation methods
  const eventWebhook = new EventWebhook();
  // Convert the public key string into an ECPublicKey
  const ecPublicKey = eventWebhook.convertPublicKeyToECDSA(publicKey);
  return eventWebhook.verifySignature(
    ecPublicKey,
    payload,
    signature,
    timestamp
  );
};

exports.handler = async (context, event, callback) => {
  // Access a pre-initialized Twilio client from context
  const twilioClient = context.getTwilioClient();
  // Access sensitive values such as the sendgrid key and phone numbers
  // from Environment Variables
  const publicKey = context.SENDGRID_WEBHOOK_PUBLIC_KEY;
  const twilioPhoneNumber = context.TWILIO_PHONE_NUMBER;
  const numberToNotify = context.NOTIFY_PHONE_NUMBER;

  // The SendGrid EventWebhookHeader provides methods for getting
  // the necessary header names.
  // Remember to cast these header names to lowercase to access them correctly
  const signatureKey = EventWebhookHeader.SIGNATURE().toLowerCase();
  const timestampKey = EventWebhookHeader.TIMESTAMP().toLowerCase();

  // Retrieve SendGrid's headers so they can be used to validate
  // the request
  const signature = event.request.headers[signatureKey];
  const timestamp = event.request.headers[timestampKey];

  // Runtime injects the request object and spreads in the SendGrid events.
  // Isolate the original SendGrid event contents using destructuring
  // and the rest operator
  const { request, ...sendGridEvents } = event;
  // Convert the SendGrid event back into an array of events, which is the
  // format sent by SendGrid initially
  const sendGridPayload = Object.values(sendGridEvents);

  // Stringify the event and add newlines/carriage returns since they're expected by validator
  const rawEvent =
    JSON.stringify(sendGridPayload).split('},{').join('},\r\n{') + '\r\n';

  // Verify the request using the public key, the body of the request,
  // and the SendGrid headers
  const valid = verifyRequest(publicKey, rawEvent, signature, timestamp);
  // Reject invalidated requests!
  if (!valid) return callback("Request didn't come from SendGrid", event);

  // Helper method to simplify repeated calls to send messages with
  // nicely formatted timestamps
  const sendSMSNotification = (recipientEmail, timestamp) => {
    const formattedDateTime = new Intl.DateTimeFormat('en-US', {
      year: 'numeric',
      month: 'numeric',
      day: 'numeric',
      hour: 'numeric',
      minute: 'numeric',
      second: 'numeric',
      hour12: true,
      timeZone: 'America/Los_Angeles',
    }).format(timestamp);

    return twilioClient.messages.create({
      from: twilioPhoneNumber,
      to: numberToNotify,
      body: `Email to ${recipientEmail} was opened on ${formattedDateTime}.`,
    });
  };

  // Convert the original list of events into a condensed version for SMS
  const normalizedEvents = sendGridPayload
    .map((rawEvent) => ({
      to: rawEvent.email,
      timestamp: rawEvent.timestamp * 1000,
      status: rawEvent.event,
      messageId: rawEvent.sg_message_id.split('.')[0],
    }))
    // Ensure that events are sorted by time to ensure they're sent
    // in the correct order
    .sort((a, b) => a.timestamp - b.timestamp);

  // Iterate over each event and wait for a text to be sent before
  // processing the next event
  for (const event of normalizedEvents) {
    // You could also await an async operation to update your db records to
    // reflect the status change here
    // await db.updateEmailStatus(event.messageId, event.status, event.timestamp);
    if (event.status === 'open') {
      await sendSMSNotification(event.to, event.timestamp);
    }
  }

  // Return a 200 OK!
  return callback();
};
```

## Create your Function and connect it to SendGrid

1. First, create a new `sendgrid-email` [Service](/docs/serverless/functions-assets/functions/create-service) and add a **Public** `/events/email` Function. Delete the default contents of the Function, and paste in the code snippet provided on this page.
2. [Create a free SendGrid account](https://signup.sendgrid.com/).
3. Follow the instructions [here](https://docs.sendgrid.com/for-developers/tracking-events/getting-started-event-webhook) to set up a SendGrid Event Webhook. Paste the URL of your newly created Function as the unique URL for the Event Webhook. (it will look like `https://sendgrid-email-5877.twil.io/events/email`)

   ![SendGrid event webhook settings with HTTP Post URL highlighted.](https://docs-resources.prod.twilio.com/526d52aeaa68b567f6a536b41422d8207d82dec8ba9e8425d4cc9664c9ec72d6.png)
4. Follow [these steps](https://docs.sendgrid.com/for-developers/tracking-events/getting-started-event-webhook-security-features#the-signed-event-webhook) to enable the Signed Event Webhook Requests. This will add signed SendGrid headers to incoming webhook requests, which we can then use to validate requests!

   ![Instructions for enabling SendGrid signed event webhook requests with a verification key.](https://docs-resources.prod.twilio.com/4cf2c3b76a6a4584e556534705e993ea06768ab2c99fa37d68067221fa7d5b76.png)
5. Copy the generated Verification Key from the last step, and save it as an [Environment variable](/docs/serverless/functions-assets/functions/variables) in Runtime as `SENDGRID_WEBHOOK_PUBLIC_KEY`. While here, also save your `TWILIO_PHONE_NUMBER` (from the Twilio console) and a `NOTIFY_PHONE_NUMBER` (this could be your personal phone number for now)

   ![Environment variables interface showing SendGrid webhook key and Twilio credentials options.](https://docs-resources.prod.twilio.com/19a084a80bc0583375e8051547f7e3e20363d31c072635daaa32e9f69eaac7a5.png)
6. Add the `@sendgrid/eventwebhook` [dependency](/docs/serverless/functions-assets/functions/dependencies) as `*`, and ensure that the `@twilio/runtime-handler` dependency is set to version `1.3.0` or later to enable headers.

   ![Node v12 dependencies list with highlighted sendgrid event webhook.](https://docs-resources.prod.twilio.com/e1b1d949f02bc8d73aa56a41f8ded2556d054d9764d6518fd8995cb9938fe1d3.png)
7. Save your Function and deploy it by clicking on **Deploy All**.

   ![Settings panel with Deploy All button for sendgrid-email-5877.twil.io.](https://docs-resources.prod.twilio.com/0cd4169da5c30d167c3841365310e875416e804b2430c3724ca044786de8ea80.png)

## Validate your code

Now that you've deployed your Function, it's time to validate that your code and its integration with SendGrid is working properly. In order to do so, you'll need to generate some email events. This will be accomplished with a short script written in JavaScript and using the `@sendgrid/mail` library.

### Setup environment variables

First, grab your [SendGrid API Key](https://app.sendgrid.com/settings/api_keys) (or create one!). For security, we'll be setting it as an environment variable and using it in our code instead of directly hard-coding it. You can do so by performing the following commands in your terminal, making sure to replace the `YOUR_API_KEY` placeholder with your own key.

```bash
echo "export SENDGRID_API_KEY='YOUR_API_KEY'" > sendgrid.env
echo "sendgrid.env" >> .gitignore
source ./sendgrid.env
```

### Install the SDK

Next, use [npm](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm) or yarn to install the Node.js SendGrid SDK which will enable you to send emails using JavaScript. If you already have [Node.js](https://nodejs.org/en/download/) installed, it's very likely you already have npm available and ready to use.

```bash
npm install --save @sendgrid/mail
```

If you prefer [yarn](https://yarnpkg.com/getting-started/install) instead:

```bash
yarn add @sendgrid/mail
```

### Add and verify a Sender Identity

Before you can successfully send an email, you'll need to verify an email address or domain in the [Sender Authentication tab](https://app.sendgrid.com/settings/sender_auth/senders). Without this, you will receive a `403 Forbidden` response when attempting to send mail.

### Send a test email

Once you have prepared your environment variables, installed the SendGrid SDK, and your email has been validated, you're ready to send some emails and create some events.

Create a new file such as `send-email.js`, and paste in the following snippet. Be sure to replace the `from` variable with your verified email address from earlier, as well as the `to` variable (in this case, you can use your verified email address here as well). Save the file.

```js
// Using Twilio SendGrid's v3 Node.js Library
// https://github.com/sendgrid/sendgrid-nodejs
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);

sgMail
  .send({
    from: 'test@example.com', // Change to your verified sender
    to: 'test@example.com', // Change to your recipient
    subject: 'Sending with Twilio SendGrid is Fun',
    text: 'and easy to do anywhere, even with Node.js',
    html: '<strong>and easy to do anywhere, even with Node.js</strong>',
  })
  .then(() => {
    console.log('Email sent');
  })
  .catch((error) => {
    console.error(error);
  });
```

Once the script is saved, you can send your test email by executing the script with Node.js:

```bash
node send-email.js
```

### Check your texts

Once you've received your email and opened it, you should receive a text message from your Function a short time later!

If you would like to expedite this process a bit and not wait for the `open` event itself, you could modify line 95 of the Function body to instead check for `delivered` events instead. A `delivered` event will be emitted and processed by your Function almost immediately after executing the `send-email` script.
