Bridge Communication
The Alien Bridge provides a type-safe communication channel between your miniapp (webview) and the Alien host application. It enables bidirectional communication through events and methods.
Overview
The bridge is designed to work only when running inside the Alien App. The host app provides the required interface at window.__miniAppsBridge__.
Development Mode: When running in a regular browser, the SDK will log warnings but won’t throw errors. This allows you to develop and test your UI, although actual communication with the host won’t be possible.
Architecture
Communication follows two main patterns:
- Events (One-way): Asynchronous notifications sent from the miniapp to the host, or vice-versa.
- Methods (Request-Response): The miniapp sends a request and waits for a specific response from the host.
Core Concepts
Event Naming Convention
All messages follow a <domain>:<action> naming convention:
- Domain: The subsystem (e.g.,
auth,storage,ui). - Action: What is happening (e.g.,
init,request,open).
Examples: auth:request, ui.modal:open, bridge:ready.
API Reference
Installing the SDK
npm install @alien-id/bridgeListening for Events
Use the on function to subscribe to events from the host app.
import { on } from '@alien-id/bridge';
const unsubscribe = on('auth:response', (payload) => {
console.log('Received auth response:', payload);
});
// To stop listening:
unsubscribe();Sending Events
Use emit to send one-way messages to the host.
import { emit } from '@alien-id/bridge';
await emit('ui:ready', {
timestamp: Date.now()
});Method Requests
Use request to send a message and wait for a response. This is the most common pattern for authentication or data fetching.
import { request } from '@alien-id/bridge';
try {
const result = await request(
'auth:request', // Method name
{ scope: ['public.name'] }, // Parameters
'auth:response' // Expected response event
);
console.log('User name:', result.name);
} catch (error) {
console.error('Auth failed:', error);
}Best Practices
- Cleanup: Always unsubscribe from events when your component unmounts to prevent memory leaks.
- Error Handling: Always wrap
request()calls intry...catchblocks as they can timeout or be rejected by the host. - Type Safety: If using TypeScript, the SDK provides full type safety for all standard events and methods.