Azure Event Grid Tutorial

Official Docs

Overview

This tutorial walks you through building a simple event-driven solution using Azure Event Grid. You'll learn how to create a topic, publish events, subscribe to those events, and handle them with a webhook endpoint.

Prerequisites

  • Azure subscription (free trial works)
  • Azure CLI installed
  • Node.js >=14 and npm
  • Git (optional)

1️⃣ Create an Event Grid Topic

Run the following Azure CLI command to create a resource group and an Event Grid topic.

az group create --name rg-eventgrid-demo --location eastus

az eventgrid topic create \
  --name myeventgridtopic \
  --resource-group rg-eventgrid-demo \
  --location eastus

2️⃣ Publish Events

Use the Azure CLI to publish a test event to the topic.

TOPIC_ENDPOINT=$(az eventgrid topic show \
  --name myeventgridtopic \
  --resource-group rg-eventgrid-demo \
  --query endpoint --output tsv)

az eventgrid event publish \
  --topic-name myeventgridtopic \
  --resource-group rg-eventgrid-demo \
  --event "{\"id\":\"1\",\"eventType\":\"Demo.Event\",\"subject\":\"Demo\",\"eventTime\":\"$(date -u +%Y-%m-%dT%H:%M:%SZ)\",\"data\":{\"message\":\"Hello Event Grid!\"},\"dataVersion\":\"1.0\"}"

3️⃣ Create a Subscription (Webhook)

First, clone the sample webhook receiver written in Node.js:

git clone https://github.com/Azure-Samples/event-grid-webhook-receiver.git
cd event-grid-webhook-receiver
npm install
npm start

The webhook will listen on http://localhost:3000/api/events. Create the subscription pointing to this endpoint:

az eventgrid event-subscription create \
  --name demo-subscription \
  --source-resource-id $(az eventgrid topic show \
    --name myeventgridtopic \
    --resource-group rg-eventgrid-demo \
    --query id -o tsv) \
  --endpoint http://YOUR_PUBLIC_IP:3000/api/events

4️⃣ Handle Events (WebHook)

The webhook code logs incoming events. Open index.js to see the handler:

app.post('/api/events', (req, res) => {
  console.log('Received events:', JSON.stringify(req.body, null, 2));
  res.status(200).send();
});

🧹 Cleanup Resources

When you're done, delete the resource group to avoid charges:

az group delete --name rg-eventgrid-demo --yes --no-wait