

# Getting started with AWS AppSync Events
<a name="event-api-getting-started"></a>

You can quickly get started with AWS AppSync Events by creating an AWS AppSync Event API and accessing it from a client. The first tutorial in this section will guide you through creating your first AWS AppSync Event API in the AWS AppSync console. Then you will learn to publish and subscribe to your event. The second tutorial guides you through creating a React app with Vite and an Amplify client. Then you will use this Amplify client to publish and subscribe messages.

**Topics**
+ [Prerequisites](event-api-prerequisites.md)
+ [Creating an AWS AppSync Event API](create-event-api-tutorial.md)
+ [Getting started with the Amplify Events client](build-amplify-app.md)

# Prerequisites
<a name="event-api-prerequisites"></a>

Before you begin the getting started tutorials, confirm that you have completed the prerequisites to get set up with an AWS account.

## Sign up for an AWS account
<a name="sign-up-for-aws"></a>

If you do not have an AWS account, complete the following steps to create one.

**To sign up for an AWS account**

1. Open [https://portal.aws.amazon.com/billing/signup](https://portal.aws.amazon.com/billing/signup).

1. Follow the online instructions.

   Part of the sign-up procedure involves receiving a phone call or text message and entering a verification code on the phone keypad.

   When you sign up for an AWS account, an *AWS account root user* is created. The root user has access to all AWS services and resources in the account. As a security best practice, assign administrative access to a user, and use only the root user to perform [tasks that require root user access](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-user.html#root-user-tasks).

AWS sends you a confirmation email after the sign-up process is complete. At any time, you can view your current account activity and manage your account by going to [https://aws.amazon.com/](https://aws.amazon.com/) and choosing **My Account**.

## Create a user with administrative access
<a name="create-an-admin"></a>

After you sign up for an AWS account, secure your AWS account root user, enable AWS IAM Identity Center, and create an administrative user so that you don't use the root user for everyday tasks.

**Secure your AWS account root user**

1.  Sign in to the [AWS Management Console](https://console.aws.amazon.com/) as the account owner by choosing **Root user** and entering your AWS account email address. On the next page, enter your password.

   For help signing in by using root user, see [Signing in as the root user](https://docs.aws.amazon.com/signin/latest/userguide/console-sign-in-tutorials.html#introduction-to-root-user-sign-in-tutorial) in the *AWS Sign-In User Guide*.

1. Turn on multi-factor authentication (MFA) for your root user.

   For instructions, see [Enable a virtual MFA device for your AWS account root user (console)](https://docs.aws.amazon.com/IAM/latest/UserGuide/enable-virt-mfa-for-root.html) in the *IAM User Guide*.

**Create a user with administrative access**

1. Enable IAM Identity Center.

   For instructions, see [Enabling AWS IAM Identity Center](https://docs.aws.amazon.com//singlesignon/latest/userguide/get-set-up-for-idc.html) in the *AWS IAM Identity Center User Guide*.

1. In IAM Identity Center, grant administrative access to a user.

   For a tutorial about using the IAM Identity Center directory as your identity source, see [ Configure user access with the default IAM Identity Center directory](https://docs.aws.amazon.com//singlesignon/latest/userguide/quick-start-default-idc.html) in the *AWS IAM Identity Center User Guide*.

**Sign in as the user with administrative access**
+ To sign in with your IAM Identity Center user, use the sign-in URL that was sent to your email address when you created the IAM Identity Center user.

  For help signing in using an IAM Identity Center user, see [Signing in to the AWS access portal](https://docs.aws.amazon.com/signin/latest/userguide/iam-id-center-sign-in-tutorial.html) in the *AWS Sign-In User Guide*.

**Assign access to additional users**

1. In IAM Identity Center, create a permission set that follows the best practice of applying least-privilege permissions.

   For instructions, see [ Create a permission set](https://docs.aws.amazon.com//singlesignon/latest/userguide/get-started-create-a-permission-set.html) in the *AWS IAM Identity Center User Guide*.

1. Assign users to a group, and then assign single sign-on access to the group.

   For instructions, see [ Add groups](https://docs.aws.amazon.com//singlesignon/latest/userguide/addgroups.html) in the *AWS IAM Identity Center User Guide*.

## Account credentials
<a name="account-credentials"></a>

Although you can use your root user credentials to access AWS AppSync, we recommend that you use an AWS Identity and Access Management (IAM) account instead. You can use the [AWSAppSyncAdministrator](https://docs.aws.amazon.com/appsync/latest/devguide/security_iam_policy_list.html#security-iam-awsmanpol-AWSAppSyncAdministrator) managed policy to grant your IAM account the correct permissions to manage your AWS AppSync resources.

## Set up the AWS Command Line Interface
<a name="set-up-cli"></a>

You can use the AWS Command Line Interface (CLI) to manage your AWS AppSync resources. For information about how to install and configure the AWS CLI, see [Getting started with the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html) in the *AWS Command Line Interface User Guide*.

# Creating an AWS AppSync Event API
<a name="create-event-api-tutorial"></a>

AWS AppSync Events allows you to create Event APIs to enable real-time capabilities in your applications. In this section, you create an API with a default channel namespace. You’ll then use the AWS AppSync console to publish messages and subscribe to messages sent to channels in the namespace.

In this tutorial you will complete the following tasks.

**Topics**
+ [Step 1: Create an event API using the AWS AppSync console](#create-event-api-console)
+ [Step 2: Publish and subscribe to receive your first event](#receive-event)
+ [Step 3: Use wildcards in your channel subscription](#use-wildcards)
+ [Step 4: Publish in batches](#publish-batches)

## Step 1: Create an event API using the AWS AppSync console
<a name="create-event-api-console"></a>

1. Sign in to the AWS Management Console and open the [AWS AppSync console](https://console.aws.amazon.com/appsync/).

1. On the AWS AppSync console service page, choose **Create API**, then choose **Event API**.

1. On the **Create Event API** page, in the **API details** section, do the following:

   1. For **API** enter the name of your API.

   1. (optional) Enter the contact name for the API.

1. Choose **Create**.

You have now created an Event API. The API is configured with API Key as an authorization mode for connect, publish, and subscribe actions. A default channel namespace with the name “default” has also been created.

To learn more about customizing authorization, see [Configuring authorization and authentication to secure Event APIs](configure-event-api-auth.md). To learn more about channel namespaces, see [Understanding channel namespaces](channel-namespaces.md)

## Step 2: Publish and subscribe to receive your first event
<a name="receive-event"></a>

Use the following instructions to publish an event.

1. In the AWS AppSync console choose the **Pub/Sub Editor** tab for the Event API that you created in step 1.

1. In the **Publish** section, for **Channel** enter **default** in the first text box and enter **/messages** in the second text box.

1. In the code editor, enter the following JSON payload.

   ```
   [{"message": "Hello world!"}]
   ```

1. Choose **Publish**.

1. The publisher logs table displays a response similar to the following to confirm success.

   ```
   {
     "failed": [],
     "successful": [
       {
         "identifier": "53287bee-ae0d-42e7-8a90-e9d2a49e4bd7",
         "index": 0
       }
     ]
   }
   ```

Now use the following instructions to subscribe to recieve messages.

1. In the **Subscribe** section of the editor, choose **Connect** to connect to your WebSocket endpoint.

1. For **Channel**, enter the name of the channel you want to subscribe to, **/default/messages**, and then choose **Subscribe**.

1. In the code editor, choose **Publish** again. You should receive a new data event in the subscriber logs table with the published event.

## Step 3: Use wildcards in your channel subscription
<a name="use-wildcards"></a>

You can specify a wildcard "\$1" at the end of a channel path to receive events published to all channels that match. Use the following instructions to set up a wildcard channel subscription for your Event API.

1. If you are still subscribed to the channel from step 2, choose **Unsubscribe**.

1. In the **Subscribe** section, for **Channel** enter **/default/\$1**.

1. In the code editor section, choose **Publish** again to send another event. You should receive a new data event in the subscriber logs table

1. In the **Publish** section, change the **Channel** name to **/default/greetings/tutorial**.

1. Choose **Publish**. You receive the message in the **Subscribe** section

## Step 4: Publish in batches
<a name="publish-batches"></a>

You can publish events in batches of up to five. Subscribed clients receive each message individually.

1. In the AWS AppSync console, continue in the **Pub/Sub Editor** tab using the Event API that you were working with in step 3.

1. In the **Publish** section JSON code editor, enter the following: 

   ```
   [
     {"message": "Hello world!"},
     {"message": "Bonjour lemonde!"},
     "Hola Mundo!"
   ]
   ```

1. Choose **Publish**.

1. In the **Subscribe** log table, you receive 3 data events.

# Getting started with the Amplify Events client
<a name="build-amplify-app"></a>

You can connect to your AWS AppSync Event API using any HTTP and WebSocket client, and you can also use the Amplify client for JavaScript. This getting started tutorial guides you through connecting to an Event API from a JavaScript React application.

In this tutorial you will complete the following tasks.

**Topics**
+ [Step 1: Create an event API](#create-event-api)
+ [Step 2: Deploy a React app with Vite](#deploy-react-vite-app)
+ [Step 3: Configure the Amplify client](#configure-amplify-client)
+ [Step 4: Connect to a channel and receive messages](#receive-message)
+ [Step 5: Send a message from your app](#send-message)

## Step 1: Create an event API
<a name="create-event-api"></a>

1. Sign in to the AWS Management Console and open the [AWS AppSync console](https://console.aws.amazon.com/appsync/).

1. On the AWS AppSync console service page, choose **Create API**, then choose **Event API**.

1. On the **Create Event API** page, in the **API details** section, do the following:

   1. For **API** enter the name of your API.

   1. (optional) Enter the contact name for the API.

1. Choose **Create**.

You have now created an Event API. The API is configured with API Key as an authorization mode for connect, publish, and subscribe actions. A default channel namespace with the name “default” has also been created.

To learn more about customizing authorization, see [Configuring authorization and authentication to secure Event APIs](configure-event-api-auth.md). To learn more about channel namespaces, see [Understanding channel namespaces](channel-namespaces.md)

## Step 2: Deploy a React app with Vite
<a name="deploy-react-vite-app"></a>

1. From your local work environment, run the following command in a terminal window to create a new Vite app for React.

   ```
   npm create vite@latest appsync-events-app -- --template react
   ```

1. Run the following command to switch to the `appsync-events-app` directory and install the dependencies and the Amplify library.

   ```
   cd appsync-events-app
   npm install
   npm install aws-amplify
   ```

1. Open a different terminal window and `cd` into your `appsync-events-app` directory. Run the following command to start your sever in dev mode.

   ```
   npm run dev
   ```

### (Optional) Configure Tailwind CSS
<a name="configure-tailwindcss"></a>

You can set up Tailwind CSS to style your project. 

1. Open a terminal window and run the following commands to install the dependencies.

   ```
   npm install -D tailwindcss postcss autoprefixer
   npx tailwindcss init -p
   ```

1. Update the `tailwind.config.js` file with the following code.

   ```
   /** @type {import('tailwindcss').Config} */
   export default {
     content: [
       "./index.html",
       "./src/**/*.{js,ts,jsx,tsx}",
     ],
     theme: {
       extend: {},
     },
     plugins: [],
   }
   ```

1. Set the content of `./src/index.css` to the following.

   ```
   @tailwind base;
   @tailwind components;
   @tailwind utilities;
   ```

1. Use the following command to start and restart your Vite app from the terminal where it is currently running.

   ```
   npm run dev
   ```

## Step 3: Configure the Amplify client
<a name="configure-amplify-client"></a>

1. Sign in to the AWS Management Console and open the [AWS AppSync console](https://console.aws.amazon.com/appsync/).

1. Open the **Integration** tab for the Event API that you created in step 1.

1. Download your configuration file.

1. Save the `amplify_outputs.json` file in your project's `src` directory. Your configuration file will look like the following.

   ```
   {
     "API": {
       "Events": {
         "endpoint": "https://abc1234567890.aws-appsync.us-west-2.amazonaws.com/event",
         "region": "us-west-2",
         "defaultAuthMode": "apiKey",
         "apiKey": "da2-your-api-key-1234567890"
       }
     }
   }
   ```
**Important**  
You must set `defaultAuthMode` to `apiKey` and *not* `API_KEY`.

## Step 4: Connect to a channel and receive messages
<a name="receive-message"></a>

1. Update your `App.jsx` file with the following code.

   ```
   import { useEffect, useState, useRef } from 'react'
   import './App.css'
   
   import { Amplify } from 'aws-amplify'
   import { events } from 'aws-amplify/data'
   import config from './amplify_outputs.json'
   
   Amplify.configure(config)
   
   export default function App() {
     const [messages, setMessages] = useState([])
     const [room, setRoom] = useState('')
     const counterRef = useRef(null)
   
     useEffect(() => {
       if (!room || !room.length) {
         return
       }
       let timeoutID
       const pr = events.connect(`/default/${room}`)
       pr.then((channel) => {
         channel.subscribe({
           next: (data) => {
             setMessages((messages) => [...messages, data.message])
             if (timeoutID) {
               clearTimeout(timeoutID);
             }
             counterRef.current?.classList.add('animate-bounce')
             timeoutID = setTimeout(() => {
               counterRef.current?.classList.remove('animate-bounce')
             }, 3000);
           },
           error: (value) => console.error(value),
         })
       })
   
       return () => {
         pr?.then((channel) => channel?.close())
       }
     }, [room])
   
     return (
       <div className='max-w-screen-md mx-auto'>
         <h2 className='my-4 p-4 font-semibold text-xl'>AppSync Events - Messages</h2>
         <button
           type="button"
           className='border rounded-md px-4 py-2 items-center text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 bg-sky-200  shadow hover:bg-sky-200/90'
           onClick={() => {
             const room = prompt('Room:')
             if (room && room.length) {
               setMessages([])
               setRoom(room.trim().replace(/\W+/g, '-'))
             }
           }}
         >
           set room
         </button>
         <div className='my-4 border-b-2  border-sky-500 py-1 flex justify-between'>
           <div>
             {room ? (
               <span>
                 Currently in room: <b>{room}</b>
               </span>
             ) : (
               <span>Pick a room to get started</span>
             )}
           </div>
           <div className='flex items-center uppercase text-xs tracking-wider font-semibold'>
             <div className='mr-2'>Messages count:</div>
             <span ref={counterRef} className='transition-all inline-flex items-center rounded-md bg-sky-100 px-2.5 py-0.5 text-xs font-medium text-sky-900'>{messages.length}</span></div>
         </div>
         <section id="messages" className='space-y-2'>
           {messages.map((message, index) => (
             <div
               key={index}
               className='border-b py-1 flex justify-between px-2'
             ><div>
                 {message}
               </div>
               <div> </div>
             </div>
           ))}
         </section>
       </div>
     )
   }
   ```

1. Open the app in your browser and choose the **set room** button to set the room to "greetings".

1. Open the AWS AppSync console, and go to the **Pub/Sub Editor** tab for your API.

1. Set your channel to `/default/greetings`. Choose the "default" namespace and set the rest of the path to `/greetings`.

1. Paste the following into the editor to send the event.

   ```
   [
       {
           "message": "hello world!"
       }
   ]
   ```

1. You should see the message in your app.

1. Choose the **set room** button again to select another room. Send another event in the Pub/Sub Editor to the `/default/greetings` channel. You do not see that message in your app.

## Step 5: Send a message from your app
<a name="send-message"></a>

1. Open your `App` component and add the following line of code at the top of the file.

   ```
   const [message, setMessage] = useState('')
   ```

1. In the same file, locate the last `section` element and add the following code.

   ```
   <section>
           <form
             disabled={!room}
             className='w-full flex justify-between mt-8'
             onSubmit={async (e) => {
               e.preventDefault()
               const event = { message }
               setMessage('')
               await events.post(`/default/${room}`, event)
             }}
           >
             <input
               type="text"
               name="message"
               placeholder="Message:"
               className='flex flex-1 rounded-md border border-input px-3 py-1 h-9 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 bg-transparent'
               value={message}
               disabled={!room}
               onChange={(e) => setMessage(e.target.value)}
             />
             <button
               type="submit"
               className='ml-4 border rounded-md px-4 flex items-center text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 bg-sky-200  shadow hover:bg-sky-200/90'
               disabled={!room || !message || !message.length}>
               <svg xmlns="http://www.w3.org/2000/svg" className='size-4' width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z" /><path d="m21.854 2.147-10.94 10.939" /></svg>
             </button>
           </form>
         </section>
   ```

1. You can now send a message to a room that you select, directly from your app.