> ## Documentation Index
> Fetch the complete documentation index at: https://docs-dev-docs-event-stream-action-templates.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

> Learn how you can create event streams using AWS EventBridge or webhooks.

# Create an Event Stream

By subscribing to events, and delivering them to a destination of your choice using event streams, you can facilitate a number of related use cases, including:

* Sending emails to new customers to welcome them or ask them to verify their email address.
* Monitoring user lifecycle changes so that you can update CRM (customer relationship management) or billing systems.

You can create an event stream using either AWS EventBridge or webhooks. The sections below outline the setup process for both options.

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  By enabling event streams, the customer becomes the controller of such information and is responsible for the data exported from the Auth0 Platform, including what information is streamed and how it is used.
</Callout>

## Access Management API (optional)

Event streams can either be provisioned using the <Tooltip tip="Auth0 Dashboard: Auth0's main product to configure your services." cta="View Glossary" href="/docs/glossary?term=Auth0+dashboard">Auth0 dashboard</Tooltip> or the [Auth0 Management API](https://auth0.com/docs/api/management/v2). If using the <Tooltip tip="Management API: A product to allow customers to perform administrative tasks." cta="View Glossary" href="/docs/glossary?term=Management+API">Management API</Tooltip>, before you can set up an event stream, you need to create a machine-to-machine (M2M) application and authenticate with a Management API token. For more information, review [Management API Access Tokens](/docs/secure/tokens/access-tokens/management-api-access-tokens).

1. Navigate to [Dashboard > Applications > Applications](https://manage.auth0.com/#/applications) and select **Create Application**.
2. Enter a descriptive name for your application and choose **Machine to Machine Applications**. Then, select **Create**.
3. Select the API you want to call from your application. In this case, use the **Auth0 Management API**.
4. Choose the permissions that you want to be issued as part of your application's access token, then select **Authorize**. For testing purposes, select:

   * `read:event_streams`
   * `create:event_streams`
   * `update:event_streams`
   * `delete:event_streams`
   * `read:event_deliveries`
   * `update:event_deliveries`
   * `create:users`
5. Navigate to the **Settings** tab to gather your **Client ID**, **Client Secret**, and **Domain**.
6. Review [Get Management API Access Tokens](/docs/secure/tokens/access-tokens/management-api-access-tokens/get-management-api-access-tokens-for-production) to retrieve and store your access token.

## AWS EventBridge

The information below describes how you can create and enable an event stream using AWS EventBridge.

### EventBridge prerequisites

To use AWS EventBridge for event streams, you will need the following:

* AWS account

  * Your AWS account must have permissions to use EventBridge. If you don’t have an account, sign up at [https://aws.amazon.com/eventbridge/](https://aws.amazon.com/eventbridge/).
* AWS IAM permissions
* AWS EventBridge event bus
* AWS account ID & region

### Create an event stream (EventBridge)

<Tabs>
  <Tab title="Management API">
    Event streams allow you to capture real-time changes within your Auth0 tenant and send them to an external system for processing.

    Before setting up an event stream, you need to identify the [event types](/docs/customize/events/event-types) you want to monitor. Then, you will use your AWS account ID and region to set up your event stream, as demonstrated below.

    This example uses the Auth0 CLI to create an event stream that subscribes to the `user.created` event, which triggers whenever a new user is registered in your tenant.

    ```bash wrap lines theme={null}
    auth0 events create --name ng-demo-eventbridge --type eventbridge --subscriptions "user.created" --configuration '{"aws_account_id":"<your-aws-account-id>","aws_region":"<your-aws-region>"}'
    ```

    If successful, this call returns the following JSON with your event stream `id`. New event streams are enabled by default.

    ```json lines theme={null}
    {
      "id": "est_8of6RXoM1997qikH7NS11h",
      "status": "enabled",
      "name": "ng-demo-eventbridge",
      "subscriptions": [
        {
          "event_type": "user.created"
        }
      ],
      "created_at": "2025-01-29T18:08:43.440Z",
      "updated_at": "2025-01-29T18:08:43.440Z",
      "destination": {
        "type": "eventbridge",
        "configuration": {
          "aws_account_id": "<your-aws-account-id>",
          "aws_region": "<your-aws-region>",
          "aws_partner_event_source": "default"
        }
      }
    }
    ```
  </Tab>

  <Tab title="Dashboard">
    To create an event stream in the Auth0 Dashboard using AWS EventBridge:

    1. Navigate to **Auth0 Dashboard** > **Event Streams (Early)**.
    2. Select **+Create Event Stream**.
    3. From the list of stream types, select **AWS EventBridge**. This will open the configuration form for your new EventBridge stream.
    4. **Configure Stream Details:** In the configuration form, you will need to provide the following information:

       * **Stream Name:**

         Enter a descriptive name for your event stream. This will help you identify it within the Auth0 Dashboard.
       * **AWS Account ID:**

         Enter the 12-digit AWS account ID where you want the Auth0 events to be sent.
       * **AWS Region:**

         Select the specific AWS Region where your EventBridge event bus is located.
    5. **Select Event Types:** In the **Select Event Types** section, choose the specific Auth0 event types you want to include in this stream. You can select multiple event types based on your requirements (e.g., `user.created`, `user.updated`, `user.deleted`).
    6. **Save Changes:** Once you have configured the stream name, AWS details, and selected your desired event types, click the **Save Changes** button.

    Your new event stream is now created, and Auth0 can begin publishing the selected event types to the specified AWS EventBridge event bus. You can monitor the status and manage your event stream from the Event Streams (Early) page in the Auth0 Dashboard.
  </Tab>

  <Tab title="Terraform">
    <Note>
      Before getting started with Terraform, you need to:

      * Install the Terraform CLI
      * Install the Auth0 CLI and authenticate with `auth0 login`
      * Have your AWS Account ID and AWS region for configuring an EventBridge stream
    </Note>

    ### File configuration

    To provision your event stream using Terraform, you need a structured project directory. See below for an example configuration when setting this up for the first time:

    ```bash theme={null}

    auth0-event-streams/
    ├── main.tf             # Core configuration: defines providers and the 'auth0_event_stream' resource.
    ├── variables.tf        # Variable declaration: defines inputs like 'aws_account_id' and 'aws_region'.
    └── terraform.tfvars    # Variable values: holds the actual configuration values (e.g., "123456789012").

    ```

    ### Define variables

    In your `variables.tf` file, declare the necessary input variables your stream configuration needs:

    ```bash theme={null}
    variable "aws_account_id" {
      description = "The 12-digit AWS Account ID where the EventBridge event bus resides."
      type        = string
    }

    variable "aws_region" {
      description = "The AWS region (e.g., us-east-1) for the EventBridge event bus."
      type        = string
    }
    ```

    ### Set variable values

    In your `terraform.tfvars` file, provide the actual values for your specific environment:

    ```bash theme={null}
    aws_account_id = "<your-aws-account-id>" # e.g., "123456789012"
    aws_region     = "<your-aws-region>"     # e.g., "us-east-1"
    ```

    ### Set environment variables

    In your terminal, set the three required environment variables using the credentials you copied in Access Management API (optional) above.

    ```bash theme={null}
    export AUTH0_DOMAIN="your-tenant-name.auth0.com"
    export AUTH0_CLIENT_ID="your_m2m_client_id"
    export AUTH0_CLIENT_SECRET="your_m2m_client_secret"
    ```

    ## Create an event stream

    This example uses the `auth0_event_stream` resource to create an event stream that subscribes to the `user.created` event, which triggers whenever a new user is registered in your tenant. Use the following sample in your `main.tf` file:

    ```hcl theme={null}
    terraform {
      required_providers {
        auth0 = {
          source  = "auth0/auth0"
          version = ">= 1.0.0" 
        }
      }
    }

    provider "auth0" {}

    resource "auth0_event_stream" "eventbridge_stream" {
      name             = "ng-demo-eventbridge-tf"
      destination_type = "eventbridge" # Required
      subscriptions    = ["user.created"]

      eventbridge_configuration {
        aws_account_id = var.aws_account_id
        aws_region     = var.aws_region
      }
    }
    ```

    If successful, this call returns the following JSON with your event stream `id`. New event streams are enabled by default.

    After you have created and saved all three of the files above, you are ready to create your stream.

    1. Initialize the provider

    ```bash theme={null}
    terraform init
    ```

    2. Review your changes:

    ```bash theme={null}
    terraform plan
    ```

    3. Create the stream:

    ```bash theme={null}
    terraform apply
    ```
  </Tab>
</Tabs>

## Webhooks

As an alternative to AWS EventBridge, you can use webhooks to facilitate event streams.

To get started, first set up a webhook handler to receive real-time notifications when a specific event occurs.  Then, you can create your event stream.

You can either create a basic webhook handler by following the instructions below, or you can use an existing service such as:

* Vercel
* Inngest

If you decide to use an existing service, you can proceed to [Create an event stream (webhook)](#create-an-event-stream-webhooks-). Otherwise, follow the instructions below to create your own basic webhook handler.

### Webhook prerequisites

Ensure you have the following installed to properly write your webhook handler:

* `node.js`
* `jq`
* `npm`
* `ngrok`

### Write the webhook handler

1. Install `express` to your `node_modules` folder and your `package.json` dependencies.

2. Install `dotenv` to your root directory to use a `.env` file for storing environment variables.

3. Create a `webhook.js` fle to receive the `user.created` event and store it in a database.

   ```javascript lines expandable theme={null}
   const express = require('express');
   const app = express();

   // Authorization middleware
   app.use((req, res, next) => {
     const token = req.headers["authorization"];
     if (token !== `Bearer ${API_TOKEN}`) {
       return res.status(401).json({ error: "Unauthorized" });
     }
     next();
   });

   // Webhook endpoint
   app.post("/webhook", async (req, res) => {
     console.log("Webhook received:", JSON.stringify(req.body, null, 2));

     const eventData = req.body;
     const { id, type, time, data } = eventData;
     const user = data.object;

     try {
       switch (type) {
         case "user.created":
           await handleUserCreated(user, time);
           break;
         case "user.updated":
           await handleUserUpdated(user, time);
           break;
         case "user.deleted":
           await handleUserDeleted(user, time);
           break;
         default:
           await handleDefaultEvent(id, type, time, data);
       }

       console.log(`Webhook event of type '${type}' committed to the database.`);
       res.sendStatus(204);
     } catch (err) {
       console.error("Error processing webhook:", err);
       res.status(500).json({ error: "Internal server error" });
     }
   });

   // Specific function for handling the user created event
   // In this example we're making sure users are also created in our own database
   async function handleUserCreated(user, time) {
     const { user_id, email, name, nickname, created_at, updated_at } = user;

     const query = `
       INSERT INTO users (user_id, email, name, nickname, created_at, updated_at, raw_user, last_event_processed)
       VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
     `;
     const values = [
       user_id,
       email,
       name,
       nickname,
       created_at,
       updated_at,
       user,
       time,
     ];

     try {
       await getPool().query(query, values);
     } catch (err) {
       if (err.code === "23505") {
         console.error(`Duplicate user_id=${user_id}, skipping insert.`);
       } else {
         console.error(`Database error while creating user_id=${user_id}:`, err);
         throw err;
       }
     }
   }
   ```

4. In the root of your project, create a `.env` file and add your API token using:

   ```bash lines theme={null}
   API_TOKEN=`openssl rand -hex 32`
   echo "API_TOKEN=$API_TOKEN" > .env
   ```

5. Start your server:

   ```bash lines theme={null}
   node webhook.js
   ```

6. To test the Webhook, expose your webhook handler using a tool like ngrok:

   ```bash lines theme={null}
   ngrok http 3000
   ```

   This provides a public URL for your local webhook handler, for example:

   ```bash lines theme={null}
   http://localhost:3000
   ```

### Create an event stream (webhooks)

Event streams allow you to capture real-time changes within your Auth0 tenant and send them to an external system for processing.

Before setting up an event stream, you need to identify the [event types](/docs/customize/events/event-types) you want to monitor. You will then use your webhook handler to create an event stream, as demonstrated below.

<Tabs>
  <Tab title="Management API">
    This example uses the Auth0 CLI to create an event stream that subscribes to the `user.created` event, which triggers whenever a new user is registered in your tenant. The event data is then forwarded to a webhook endpoint for further processing.

    ```bash lines theme={null}
    source .env # Make sure you are in the webhook directory where you created your .env file
    WEBHOOK_URL="<ngrok URL>/webhook"

    auth0 events create -n my-event1 -t webhook -s "user.created" -c '{"webhook_endpoint":"'"${WEBHOOK_URL}"'","webhook_authorization":{"method":"bearer","token":'"${API_TOKEN}"'"}}'
    ```

    If successful, this returns the following JSON with your event stream `id`. New event streams are enabled by default.

    ```hcl theme={null}
    {
      "id": "est_8of6RXoM1997qikH7NS11h",
      "status": "enabled",
      "name": "ng-demo-2",
      "subscriptions": [
        {
          "event_type": "user.created"
        }
      ],
      "created_at": "2025-01-29T18:08:43.440Z",
      "updated_at": "2025-01-29T18:08:43.440Z",
      "destination": {
        "type": "webhook",
        "configuration": {
          "webhook_endpoint": "https://example.com/webhook",
          "webhook_authorization": {
            "method": "bearer"
          }
        }
      }
    }
    ```

    #### Verify the event stream

    After you create an event stream, you can verify that the event stream exists using the following command:

    ```bash lines theme={null}
    auth0 events show <EVENT_STREAM_ID>
    ```
  </Tab>

  <Tab title="Dashboard">
    To create an event stream in the Auth0 Dashboard using AWS EventBridge:

    1. Navigate to **Auth0 Dashboard** > **Event Streams (Early)**.
    2. Select **+Create Event Stream**.
    3. From the list of stream types, select **Webhook**. This will open the configuration form for your new webhook stream.
    4. **Configure Stream Details:** In the configuration form, you will need to provide the following information:

       * **Stream Name:**

         Enter a descriptive name for your event stream. This will help you identify it within the Auth0 Dashboard.
       * **Endpoint:** Enter the complete URL of the HTTP endpoint where you want Auth0 to send the events. This is the service that will receive and process the event data.
       * **Authentication Method:** Choose the authentication method required by your endpoint.
       * **Authorization Token:** If you selected **Bearer Token** as the authentication method, enter the required authorization token here.
    5. **Select Event Types:** In the **Select Event Types** section, choose the specific Auth0 event types you want to include in this stream. You can select multiple event types based on your requirements (e.g., `user.created`, `user.updated`, `user.deleted`).
    6. **Save Changes:** Once you have configured the stream name, AWS details, and selected your desired event types, click the **Save Changes** button.

    Your new event stream is now created, and Auth0 can begin publishing the selected event types to the specified Webhook. You can monitor the status and manage your event stream from the Event Streams (Early) page in the Auth0 Dashboard.
  </Tab>

  <Tab title="Terraform">
    ### File configuration

    To provision your event stream using Terraform, you'll need a structured project directory. See below for an example configuration when setting this up for the first time:

    ```bash theme={null}
    auth0-event-streams/
    ├── main.tf             # Core configuration: defines providers and the 'auth0_event_stream' resource.
    ├── variables.tf        # Variable declaration: defines inputs like 'aws_account_id' and 'aws_region'.
    └── terraform.tfvars    # Variable values: holds the actual configuration values (e.g., "123456789012").
    ```

    ### Define variables

    In your `variables.tf` file, declare the necessary input variables your stream configuration will need:

    ```bash theme={null}
    variable "api_token" {
      description = "The secret token used for Webhook Bearer Authorization."
      type        = string
      sensitive   = true 
    }

    variable "webhook_endpoint_url" {
      description = "The public HTTPS URL for the webhook handler (e.g., your ngrok URL)."
      type        = string
    }
    ```

    ### Environment configuration

    Using the API token generated above, securely set the environment variable in your terminal using the `TF_VAR_` prefix:

    ```bash wrap lines theme={null}
    export AUTH0_DOMAIN="your-tenant-name.auth0.com"
    export AUTH0_CLIENT_ID="your_m2m_client_id"
    export AUTH0_CLIENT_SECRET="your_m2m_client_secret"
    ```

    If successful, this returns the following JSON with your event stream `id`. New event streams are enabled by default.

    ```bash theme={null}
    export TF_VAR_api_token="${API_TOKEN}"

    export AUTH0_DOMAIN="your-tenant-name.auth0.com"
    export AUTH0_CLIENT_ID="your_m2m_client_id"
    export AUTH0_CLIENT_SECRET="your_m2m_client_secret"
    ```

    ## Create an event stream

    This example uses the `auth0_event_stream` resource to create an event stream that subscribes to the `user.created` event, which triggers whenever a new user is registered in your tenant. Use the following sample in your `main.tf` file:

    If successful, this call returns the following JSON with your event stream `id`. New event streams are enabled by default.

    ```hcl theme={null}
    terraform {
      required_providers {
        auth0 = {
          source  = "auth0/auth0"
          version = ">= 1.0.0" 
        }
      }
    }

    provider "auth0" {}

    resource "auth0_event_stream" "webhook_stream" {
      name             = "my-webhook-handler-stream-tf"
      destination_type = "webhook" 
      subscriptions    = ["user.created"] 

      webhook_configuration {
        webhook_endpoint = var.webhook_endpoint_url

        webhook_authorization {
          method = "bearer"
          token  = var.api_token 
        }
      }
    }
    ```

    After you have created and saved all three of the files above, you are ready to create your stream.

    1. Initialize the provider

    ```bash theme={null}
    terraform init
    ```

    2. Run the plan:

    ```bash theme={null}
    URL="<your-ngrok-url>/webhook"
    terraform plan -var="webhook_endpoint_url=${URL}"
    ```

    3. Create the stream:

    ```bash theme={null}
    terraform apply -var="webhook_endpoint_url=https://<your-ngrok-url>/webhook"
    ```
  </Tab>
</Tabs>

After the stream is active, you can test the event stream. For more information, review [**Event Testing, Observability, and Failure Recovery**](/docs/customize/events/event-testing-observability-and-failure-recovery).

## Auth0 Actions

The information below describes how you can create and enable an event stream using Auth0 Actions.

### Create an event stream (Actions)

<Tabs>
  <Tab title="Management API">
    Event streams allow you to capture real-time changes within your Auth0 tenant and send them to an external system for processing.

    Before setting up an event stream, you need to identify the [event types](/docs/customize/events/event-types) you want to monitor. This example uses the Auth0 CLI to create an event stream that subscribes to the `user.created` event, which triggers whenever your tenant registers a new user.

    ```bash wrap lines theme={null}
    auth0 event-streams create \
      --name actions-1 \
      --type action \
      --subscriptions "user.created,user.updated,user.deleted" \
      --configuration '{"action_id":"385db79f-28a4-43d9-909d-6f5511dd6632"}'
    ```

    If successful, this call returns the following JSON with your event stream `id`. New event streams are enabled by default.

    ```json lines theme={null}
    {
        "configuration": {
          "action_id": "act_xyz789...",
          "status": "enabled"
      }
    }
    ```
  </Tab>

  <Tab title="Dashboard">
    To create an event stream in the Auth0 Dashboard using Auth0 Actions:

    1. Navigate to **Auth0 Dashboard** > **Event Streams (Early)**.

    2. Select **+Create Event Stream**.                .

    3. From the list of stream types, select **+Auth0 Actions**. This opens the configuration form for your new Auth0 Actions stream.

    4. **Configure Stream Details:** In the configuration form, you need to provide the following information:

       * **Stream Name:**

         Enter a descriptive name for your event stream. This will help you identify it within the Auth0 Dashboard.

    5. **Select Event Types:** In the **Select Event Types** section, choose the specific Auth0 event types you want to include in this stream. You can select multiple event types based on your requirements (e.g., `Created`, `Updated`, `Deleted`).

    6. In the **Action Editor**, write your handler code. The system requires the `onExecuteEventStream` function. You can use the `api` object to manage success or failure states.

    ```javascript theme={null}
    /**
     * Handler that will be called during the execution of an Event Stream.
     * @param {Event} event - Details about the Cloud Event.
     * @param {EventStreamAPI} api - Interface whose methods can be used to handle the event.
     */
    exports.onExecuteEventStream = async (event, api) => {
      const eventType = event.message.type;
      const eventData = event.message.data;

      console.log(`Received event: ${eventType}`);

      // Custom Logic: e.g., Send data to an external API
      // await axios.post('https://my-crm.com/ingest', eventData);

      // FAILURE HANDLING:
      // To trigger a retry, either throw an error or use api.message.fail()
      if (!eventData) {
         // api.message.fail('No data received');
         throw new Error('No data received');
      }

      // SUCCESS:
      // If the function ends without error, the event is marked delivered.
    };
    ```

    7. **Save Changes:** Once you have configured the stream name and Action handler, the system automatically creates the Action, bind it to a stream, and enables it.

    Your new event stream is now created, and Auth0 can begin publishing the selected event types to the specified Auth0 Action. You can monitor the status and manage your event stream from the Event Streams (Early) page in the Auth0 Dashboard.
  </Tab>
</Tabs>

## Learn more

* [Event Types](/docs/customize/events/event-types)
* [Event Testing, Observability, and Failure Recovery](/docs/customize/events/event-testing-observability-and-failure-recovery)
* [Events Best Practices](/docs/customize/events/events-best-practices)
