Connect to AWS AppSync Events
This guide walks through how you can connect to AWS AppSync Events using the Amplify library.
AWS AppSync Events lets you create secure and performant serverless WebSocket APIs that can broadcast real-time event data to millions of subscribers, without you having to manage connections or resource scaling. With this feature, you can build multi-user features such as a collaborative document editors, chat apps, and live polling systems.
Learn more about AWS AppSync Events by visiting the Developer Guide.
Connect to an Event API without an existing Amplify backend
Before you begin, you will need:
- An Event API created via the AWS Console
- Take note of: HTTP endpoint, region, API Key
src/App.tsx
import type { EventsChannel } from 'aws-amplify/data';import { useState, useEffect } from 'react';import { Amplify } from 'aws-amplify';import { events } from 'aws-amplify/data';
Amplify.configure({ API: { Events: { endpoint: 'https://abcdefghijklmnopqrstuvwxyz.appsync-api.us-east-1.amazonaws.com/event', region: 'us-east-1', defaultAuthMode: 'apiKey', apiKey: 'da2-abcdefghijklmnopqrstuvwxyz' } }});
export default function App() { const [myEvents, setMyEvents] = useState<unknown[]>([]);
useEffect(() => { let channel: EventsChannel;
const connectAndSubscribe = async () => { channel = await events.connect('default/channel');
channel.subscribe({ next: (data) => { console.log('received', data); setMyEvents((prev) => [data, ...prev]); }, error: (err) => console.error('error', err) }); };
connectAndSubscribe();
return () => channel && channel.close(); }, []);
async function publishEvent() { await events.post('default/channel', { some: 'data' }); }
return ( <> <button onClick={publishEvent}>Publish Event</button> <ul> {myEvents.map((event, index) => ( <li key={index}>{JSON.stringify(event)}</li> ))} </ul> </> );}
Connect to an Event API with an existing Amplify backend
Coming Soon