A lightweight TypeScript client for AWS AppSync Events API with React hooks support.
This library provides a client for interacting with AWS AppSync Events API, enabling real-time event publishing and subscription capabilities for your applications. It offers a streamlined interface for connecting to AppSync WebSocket endpoints with automatic reconnection support, flexible authentication options, and React hooks for easy integration.
AWS AppSync Events allows you to build scalable real-time applications that can broadcast events to millions of subscribers without managing complex WebSocket infrastructure.
- π WebSocket-based real-time event subscriptions
- π Multiple authentication methods support (API Key, Cognito, OIDC, Custom)
- π Automatic reconnection with exponential backoff
- π Custom domain support
- π§© React hooks for seamless integration with React applications
- π¦ Lightweight with minimal dependencies
- π Full TypeScript support with proper type definitions
npm install ob-appsync-events-clientimport { AppSyncEventsClient } from "ob-appsync-events-client";
// Initialize the client
const client = new AppSyncEventsClient(
"https://your-appsync-endpoint.appsync-api.region.amazonaws.com/event",
{
apiKey: "your-api-key", // For API Key auth mode
// OR
// authorization: 'your-token',
// OR
// authorization: async () => await getValidToken(),
},
);
// Connect to AppSync Events API
await client.connect();
// Subscribe to a channel
const subscription = await client.subscribe("myChannel", (data) => {
console.log("Received data:", data);
});
// Publish to a channel
client.publish("myChannel", { message: "Hello, world!" });
// Later, unsubscribe when done
subscription.unsubscribe();
// Disconnect when completely done
client.disconnect();import { useChannel } from "ob-appsync-events-client";
import { AppSyncEventsClient } from "ob-appsync-events-client";
// Create client instance (best done outside component or in a context)
const client = new AppSyncEventsClient(
"https://your-appsync-endpoint.appsync-api.region.amazonaws.com/event",
{
apiKey: "your-api-key",
},
);
function MyComponent() {
// Subscribe to messages
const [subscription, isReady] = useChannel(client, "myChannel", (data) => {
console.log("New message:", data);
});
// Send a message
const sendMessage = () => {
if (isReady) {
subscription.publish({
text: "Hello from React!",
timestamp: Date.now(),
});
}
};
return (
<div>
<p>Connection status: {isReady ? "Connected" : "Connecting..."}</p>
<button onClick={sendMessage} disabled={!isReady}>
Send Message
</button>
</div>
);
}The main client for interacting with AWS AppSync Events API.
constructor(httpEndpoint: string, options: ClientOptions)httpEndpoint: The HTTP endpoint of your AppSync APIoptions: Configuration optionsregion?: AWS region (optional)apiKey?: API key for apiKey authentication modeauthorization?: Authorization token or token provider functionstring: Static token for authentication() => Promise<string>: Function that returns a Promise resolving to a token
connect(): Establishes a WebSocket connection and returns a Promisesubscribe<T>(channel: string, callback: (data: T) => void, subscriptionId?: string): Subscribes to a channelpublish(channel: string, ...data: any[]): Publishes data to a channel (async)getChannel(channel: string): Gets a channel for publishing without subscribingdisconnect(): Closes the WebSocket connection and cleans up resources
function useChannel<T>(
client: AppSyncEventsClient,
channel: string,
callback?: (data: T) => void,
): [SubscriptionInfo, boolean];A React hook for subscribing to an AppSync Events channel, handling subscription lifecycle and cleanup automatically.
client: The AppSyncEventsClient instancechannel: The channel name to subscribe tocallback: Optional callback function invoked when events are received- Returns: A tuple containing:
SubscriptionInfo: Object with subscription details and methodsboolean: Ready state flag indicating if the subscription is active
The library supports all authentication methods available in AWS AppSync:
const client = new AppSyncEventsClient(endpoint, {
apiKey: "your-api-key",
});const client = new AppSyncEventsClient(endpoint, {
authorization: "your-token", // JWT token from Cognito, OIDC, or custom auth
});const client = new AppSyncEventsClient(endpoint, {
authorization: async () => {
// Fetch or refresh token dynamically
const token = await getValidToken();
return token;
},
});- Real-time chat applications
- Live dashboards and analytics
- Sports and gaming updates
- Collaborative editing tools
- Notification systems
- IoT device monitoring
This library works in all modern browsers that support WebSockets and JavaScript Promises. It does not require any polyfills for most environments.
This project uses TypeScript and Vite for development and building. The library code is located in the lib directory.
# Install dependencies
npm install# Build the library
npm run build
# Run formatting
npm run format
# Run linting
npm run lintob-appsync-events-client/
βββ lib/ # Library source code
β βββ appsync-events-client.ts # Main client implementation
β βββ react-hooks.ts # React hooks for the client
β βββ main.ts # Public exports
βββ dist/ # Built library output (generated)
βββ package.json # Package configuration
MIT