Verify SendGrid webhooks

SendGrid can sign each Event Webhook POST, so you can confirm it came from SendGrid and wasn't changed, but signing is off until you turn it on for a webhook. X-Twilio-Email-Event-Webhook-Signature then holds a base64 ECDSA signature over a SHA-256 hash of the X-Twilio-Email-Event-Webhook-Timestamp value followed by the raw body, and you check it with that webhook's public key. SendGrid's libraries have a helper for this, such as @sendgrid/eventwebhook for Node.js.

These pages cover the Event Webhook, which reports on email you send. Inbound Parse, which posts email you receive as multipart/form-data, has no event types and is covered in the Production guide.

The facts

Signature header
x-twilio-email-event-webhook-signature

Not every delivery is signed: check your setup.

Scheme
ECDSA

Asymmetric: verify with the vendor's public key.

Signed material
{timestamp}{raw body}

The X-Twilio-Email-Event-Webhook-Timestamp value as sent, then the body's raw bytes, with nothing between them. The signature covers a SHA-256 hash of that.

Send timestamp
x-twilio-email-event-webhook-timestamp
What to build
Verify with the vendor's public key
Key
public key

SendGrid webhook public key

There's no shared secret. SendGrid generates a key pair for each signed webhook, keeps the private key and shows you the public key, which is what you verify with. It isn't your API key.

  • In the SendGrid UI: go to Settings > Mail Settings > Event Webhooks, edit the webhook, turn on Enable Signed Event Webhook and select Save. Then open it again to copy the key.
  • From the API: Get an Event Webhook returns it as public_key, but only for a webhook with signature verification on.
  • One per webhook: each signed webhook has its own key pair, so with several webhooks you need the matching key.
  • Format: a base64 string in the docs' example (MFkwEwYH...). SendGrid's Node.js helper converts it with convertPublicKeyToECDSA, and its Python helper with convert_public_key_to_ecdsa.
  • Replacing it: turning signing off and selecting Save deletes the key pair. Turning it back on generates a new one, so update your stored key. The docs describe no other rotation and no test and live split.

Source: SendGrid docs ↗

Code

express/src/index.js
javascript
require('dotenv').config();
const express = require('express');
const crypto = require('crypto');

const app = express();
const port = process.env.PORT || 3000;

/**
 * Verify SendGrid webhook signature using ECDSA
 */
function verifySignature(publicKey, payload, signature, timestamp) {
  try {
    // Decode the base64 signature
    const decodedSignature = Buffer.from(signature, 'base64');

    // Create the signed content: timestamp + payload
    const signedContent = timestamp + payload;

    // Create verifier with SHA256
    const verifier = crypto.createVerify('sha256');
    verifier.update(signedContent);

    // Add PEM headers if not present
    let pemKey = publicKey;
    if (!pemKey.includes('BEGIN PUBLIC KEY')) {
      pemKey = `-----BEGIN PUBLIC KEY-----\n${publicKey}\n-----END PUBLIC KEY-----`;
    }

    // Verify the signature using the public key
    return verifier.verify(pemKey, decodedSignature);
  } catch (error) {
    console.error('Signature verification error:', error);
    return false;
  }
}

// Health check endpoint
app.get('/health', (req, res) => {
  res.json({ status: 'ok' });
});

// SendGrid webhook endpoint - MUST use raw body for signature verification
app.post('/webhooks/sendgrid', express.raw({ type: 'application/json' }), (req, res) => {
  // Get signature headers (check both cases for compatibility)
  const signature = req.get('X-Twilio-Email-Event-Webhook-Signature') ||
                    req.get('x-twilio-email-event-webhook-signature');
  const timestamp = req.get('X-Twilio-Email-Event-Webhook-Timestamp') ||
                    req.get('x-twilio-email-event-webhook-timestamp');

  // Validate required headers
  if (!signature || !timestamp) {
    console.error('Missing required headers');
    return res.status(400).json({ error: 'Missing signature headers' });
  }

  const publicKey = process.env.SENDGRID_WEBHOOK_VERIFICATION_KEY;
  if (!publicKey) {
    console.error('SENDGRID_WEBHOOK_VERIFICATION_KEY not configured');
    return res.status(500).json({ error: 'Webhook verification not configured' });
  }

  // Get raw payload as string
  const payload = req.body.toString();

  // Verify signature
  if (!verifySignature(publicKey, payload, signature, timestamp)) {
    console.error('Invalid signature');
    return res.status(400).json({ error: 'Invalid signature' });
  }

  // Parse and process events
  let events;
  try {
    events = JSON.parse(payload);
  } catch (error) {
    console.error('Invalid JSON payload:', error);
    return res.status(400).json({ error: 'Invalid JSON payload' });
  }

  // Process each event
  console.log(`Received ${events.length} SendGrid events`);

  for (const event of events) {
    console.log(`Event: ${event.event} for ${event.email} at ${new Date(event.timestamp * 1000).toISOString()}`);

    // Handle specific event types
    switch (event.event) {
      case 'delivered':
        console.log(`Email delivered to ${event.email}`);
        break;
      case 'bounce':
        console.log(`Email bounced for ${event.email}: ${event.reason}`);
        // Update your database to mark email as invalid
        break;
      case 'spam report':
        console.log(`Spam report from ${event.email}`);
        // Remove from mailing lists
        break;
      case 'unsubscribe':
        console.log(`Unsubscribe from ${event.email}`);
        // Update subscription preferences
        break;
      case 'group unsubscribe':
        console.log(`Group unsubscribe from ${event.email}`);
        // Update group subscription preferences
        break;
      case 'group resubscribe':
        console.log(`Group resubscribe from ${event.email}`);
        // Update group subscription preferences
        break;
      case 'open':
        console.log(`Email opened by ${event.email}`);
        // Track engagement metrics
        break;
      case 'click':
        console.log(`Link clicked by ${event.email}: ${event.url}`);
        // Track click analytics
        break;
      case 'deferred':
        console.log(`Email deferred for ${event.email}: ${event.reason}`);
        // Monitor delivery issues
        break;
      case 'dropped':
        console.log(`Email dropped for ${event.email}: ${event.reason}`);
        // Investigate drop reasons
        break;
      case 'processed':
        console.log(`Email processed for ${event.email}`);
        // Track processing status
        break;
      default:
        console.log(`Unhandled event type: ${event.event}`);
    }
  }

  // Return 200 to acknowledge receipt
  res.sendStatus(200);
});

// Start server only when not in test environment
let server;
if (process.env.NODE_ENV !== 'test') {
  server = app.listen(port, () => {
    console.log(`SendGrid webhook server listening on port ${port}`);
    console.log(`Webhook endpoint: http://localhost:${port}/webhooks/sendgrid`);
  });
}

// For testing
module.exports = { app, server };
nextjs/app/webhooks/sendgrid/route.ts
typescript
import { NextRequest, NextResponse } from 'next/server';
import { createVerify } from 'crypto';

/**
 * Verify SendGrid webhook signature using ECDSA
 */
function verifySignature(
  publicKey: string,
  payload: string,
  signature: string,
  timestamp: string
): boolean {
  try {
    // Decode the base64 signature
    const decodedSignature = Buffer.from(signature, 'base64');

    // Create the signed content: timestamp + payload
    const signedContent = timestamp + payload;

    // Create verifier with SHA256
    const verifier = createVerify('sha256');
    verifier.update(signedContent);

    // Add PEM headers if not present
    let pemKey = publicKey;
    if (!pemKey.includes('BEGIN PUBLIC KEY')) {
      pemKey = `-----BEGIN PUBLIC KEY-----\n${publicKey}\n-----END PUBLIC KEY-----`;
    }

    // Verify the signature using the public key
    return verifier.verify(pemKey, decodedSignature);
  } catch (error) {
    console.error('Signature verification error:', error);
    return false;
  }
}

export async function POST(request: NextRequest) {
  // Get signature headers (check both cases for compatibility)
  const signature =
    request.headers.get('X-Twilio-Email-Event-Webhook-Signature') ||
    request.headers.get('x-twilio-email-event-webhook-signature');
  const timestamp =
    request.headers.get('X-Twilio-Email-Event-Webhook-Timestamp') ||
    request.headers.get('x-twilio-email-event-webhook-timestamp');

  // Validate required headers
  if (!signature || !timestamp) {
    console.error('Missing required headers');
    return NextResponse.json(
      { error: 'Missing signature headers' },
      { status: 400 }
    );
  }

  const publicKey = process.env.SENDGRID_WEBHOOK_VERIFICATION_KEY;
  if (!publicKey) {
    console.error('SENDGRID_WEBHOOK_VERIFICATION_KEY not configured');
    return NextResponse.json(
      { error: 'Webhook verification not configured' },
      { status: 500 }
    );
  }

  // Get raw payload as string - IMPORTANT: must be raw bytes
  const payload = await request.text();

  // Verify signature
  if (!verifySignature(publicKey, payload, signature, timestamp)) {
    console.error('Invalid signature');
    return NextResponse.json(
      { error: 'Invalid signature' },
      { status: 400 }
    );
  }

  // Parse and process events
  let events;
  try {
    events = JSON.parse(payload);
  } catch (error) {
    console.error('Invalid JSON payload:', error);
    return NextResponse.json(
      { error: 'Invalid JSON payload' },
      { status: 400 }
    );
  }

  // Process each event
  console.log(`Received ${events.length} SendGrid events`);

  for (const event of events) {
    console.log(
      `Event: ${event.event} for ${event.email} at ${new Date(
        event.timestamp * 1000
      ).toISOString()}`
    );

    // Handle specific event types
    switch (event.event) {
      case 'delivered':
        console.log(`Email delivered to ${event.email}`);
        // Update delivery status in your database
        break;
      case 'bounce':
        console.log(`Email bounced for ${event.email}: ${event.reason}`);
        // Update your database to mark email as invalid
        break;
      case 'spam report':
        console.log(`Spam report from ${event.email}`);
        // Remove from mailing lists
        break;
      case 'unsubscribe':
        console.log(`Unsubscribe from ${event.email}`);
        // Update subscription preferences
        break;
      case 'group unsubscribe':
        console.log(`Group unsubscribe from ${event.email}`);
        // Update group subscription preferences
        break;
      case 'group resubscribe':
        console.log(`Group resubscribe from ${event.email}`);
        // Update group subscription preferences
        break;
      case 'open':
        console.log(`Email opened by ${event.email}`);
        // Track engagement metrics
        break;
      case 'click':
        console.log(`Link clicked by ${event.email}: ${event.url}`);
        // Track click analytics
        break;
      case 'deferred':
        console.log(`Email deferred for ${event.email}: ${event.reason}`);
        // Monitor delivery issues
        break;
      case 'dropped':
        console.log(`Email dropped for ${event.email}: ${event.reason}`);
        // Investigate drop reasons
        break;
      case 'processed':
        console.log(`Email processed for ${event.email}`);
        // Track processing status
        break;
      default:
        console.log(`Unhandled event type: ${event.event}`);
    }
  }

  // Return 200 to acknowledge receipt
  return new NextResponse(null, { status: 200 });
}

// Health check endpoint
export async function GET() {
  return NextResponse.json({ status: 'ok', endpoint: '/webhooks/sendgrid' });
}
fastapi/main.py
python
import os
import base64
import json
from datetime import datetime
from typing import List, Dict, Any
from fastapi import FastAPI, Header, Request, HTTPException
from fastapi.responses import JSONResponse
from dotenv import load_dotenv
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.exceptions import InvalidSignature

# Load environment variables
load_dotenv()

app = FastAPI(title="SendGrid Webhook Handler")


def verify_signature(
    public_key_str: str,
    payload: bytes,
    signature: str,
    timestamp: str
) -> bool:
    """Verify SendGrid webhook signature using ECDSA"""
    try:
        # Decode the base64 signature
        decoded_signature = base64.b64decode(signature)

        # Create the signed content: timestamp + payload
        signed_content = (timestamp + payload.decode('utf-8')).encode('utf-8')

        # Add PEM headers if not present
        if not public_key_str.startswith('-----BEGIN'):
            public_key_pem = f"-----BEGIN PUBLIC KEY-----\n{public_key_str}\n-----END PUBLIC KEY-----"
        else:
            public_key_pem = public_key_str

        # Parse the public key
        public_key = serialization.load_pem_public_key(public_key_pem.encode())

        # Verify the signature
        public_key.verify(
            decoded_signature,
            signed_content,
            ec.ECDSA(hashes.SHA256())
        )
        return True
    except (InvalidSignature, Exception) as e:
        print(f"Signature verification failed: {e}")
        return False


@app.get("/health")
async def health_check():
    """Health check endpoint"""
    return {"status": "ok"}


@app.post("/webhooks/sendgrid")
async def handle_sendgrid_webhook(
    request: Request,
    x_twilio_email_event_webhook_signature: str = Header(None, alias="X-Twilio-Email-Event-Webhook-Signature"),
    x_twilio_email_event_webhook_timestamp: str = Header(None, alias="X-Twilio-Email-Event-Webhook-Timestamp")
):
    """Handle SendGrid webhook events"""

    # Check for lowercase headers as fallback
    if not x_twilio_email_event_webhook_signature:
        x_twilio_email_event_webhook_signature = request.headers.get("x-twilio-email-event-webhook-signature")
    if not x_twilio_email_event_webhook_timestamp:
        x_twilio_email_event_webhook_timestamp = request.headers.get("x-twilio-email-event-webhook-timestamp")

    # Validate required headers
    if not x_twilio_email_event_webhook_signature or not x_twilio_email_event_webhook_timestamp:
        raise HTTPException(status_code=400, detail="Missing signature headers")

    # Get public key from environment
    public_key = os.getenv("SENDGRID_WEBHOOK_VERIFICATION_KEY")
    if not public_key:
        raise HTTPException(status_code=500, detail="Webhook verification not configured")

    # Get raw payload - IMPORTANT: must be raw bytes for signature verification
    payload = await request.body()

    # Verify signature
    if not verify_signature(public_key, payload, x_twilio_email_event_webhook_signature, x_twilio_email_event_webhook_timestamp):
        raise HTTPException(status_code=400, detail="Invalid signature")

    # Parse JSON payload
    try:
        events = json.loads(payload)
    except json.JSONDecodeError:
        raise HTTPException(status_code=400, detail="Invalid JSON payload")

    # Process each event
    print(f"Received {len(events)} SendGrid events")

    for event in events:
        event_time = datetime.fromtimestamp(event['timestamp']).isoformat()
        print(f"Event: {event['event']} for {event['email']} at {event_time}")

        # Handle specific event types
        match event.get('event'):
            case 'delivered':
                print(f"Email delivered to {event['email']}")
                # Update delivery status in your database
            case 'bounce':
                print(f"Email bounced for {event['email']}: {event.get('reason', 'Unknown')}")
                # Update your database to mark email as invalid
            case 'spam report':
                print(f"Spam report from {event['email']}")
                # Remove from mailing lists
            case 'unsubscribe':
                print(f"Unsubscribe from {event['email']}")
                # Update subscription preferences
            case 'group unsubscribe':
                print(f"Group unsubscribe from {event['email']}")
                # Update group subscription preferences
            case 'group resubscribe':
                print(f"Group resubscribe from {event['email']}")
                # Update group subscription preferences
            case 'open':
                print(f"Email opened by {event['email']}")
                # Track engagement metrics
            case 'click':
                print(f"Link clicked by {event['email']}: {event.get('url', 'Unknown')}")
                # Track click analytics
            case 'deferred':
                print(f"Email deferred for {event['email']}: {event.get('reason', 'Unknown')}")
                # Monitor delivery issues
            case 'dropped':
                print(f"Email dropped for {event['email']}: {event.get('reason', 'Unknown')}")
                # Investigate drop reasons
            case 'processed':
                print(f"Email processed for {event['email']}")
                # Track processing status
            case _:
                print(f"Unhandled event type: {event.get('event')}")

    # Return 200 to acknowledge receipt
    return JSONResponse(content={"status": "ok"}, status_code=200)


if __name__ == "__main__":
    import uvicorn
    port = int(os.getenv("PORT", 3000))
    uvicorn.run(app, host="0.0.0.0", port=port)

From hookdeck/webhook-skills ↗

Or install the SendGrid webhooks skill:

npx skills add hookdeck/webhook-skills --skill sendgrid-webhooks

Common failures

Body parsed before verification

SendGrid signs the raw bytes, and converting them to a JSON string can remove characters that were signed. Verify before any parsing.

Key pair not saved yet

SendGrid only generates the key pair when you save the webhook, so Test Integration before that doesn't test signing. Turning signing off and saving deletes the pair.

Another webhook's public key

Each signed webhook has its own key pair. With several webhooks, use the public key of the one that sent the request.

Public key in the wrong form

The key is a base64 string. SendGrid's Node.js helper needs it converted with convertPublicKeyToECDSA first, and its Python helper with convert_public_key_to_ecdsa.

From Hookdeck's SendGrid guide

Let Event Gateway verify SendGrid signatures.

Event Gateway verifies the signature on each SendGrid delivery before it reaches your service, then queues it and retries failures on your schedule.

Not affiliated with SendGrid. Facts are compiled from public sources and linked inline.