miniapp-bridge-innovix
v0.1.0
Published
TypeScript bridge client for Flutter WebView and Flutter Web iframe hosts.
Readme
miniapp-bridge
TypeScript client for web apps hosted in a Flutter mobile WebView or Flutter Web iframe. The web app sends typed requests to Flutter; the host handles permissions and native work and returns structured results.
Install
npm install miniapp-bridgeReact is an optional peer dependency, needed only for the miniapp-bridge/react hooks.
Quick start
Run the page inside a compatible Flutter host. In a regular browser, bridge requests return BRIDGE_UNAVAILABLE.
import { bridge } from "miniapp-bridge";
const connection = await bridge.ping();
if (!connection.ok) {
console.error(connection.error.code, connection.error.message);
} else {
console.log(connection.data.message); // "pong"
}
const position = await bridge.location.getCurrentPosition();
if (position.ok) {
console.log(position.data.latitude, position.data.longitude);
}Every method returns Promise<BridgeResult<T>>:
type BridgeResult<T> =
| { ok: true; data: T }
| { ok: false; error: { code: BridgeErrorCode; message: string; details?: unknown } };Expected failures resolve with ok: false; check ok before reading data or error.
API
Import the shared bridge, or create new SuperAppBridgeClient(options). All methods below return a bridge result.
| Feature | Method | Success data |
| --- | --- | --- |
| Connection | bridge.ping(timeoutMs?) | { message: "pong", platform: "flutter", timestamp } |
| Contacts | bridge.contacts.permissionStatus() | PermissionState |
| Contacts | bridge.contacts.pick(timeoutMs?) | Contact |
| Location | bridge.location.permissionStatus() | PermissionState |
| Location | bridge.location.getCurrentPosition(timeoutMs?) | Coordinates |
| Notifications | bridge.notifications.permissionStatus() | PermissionState |
| Notifications | bridge.notifications.requestPermission() | PermissionState |
| Notifications | bridge.notifications.show({ title, body?, data? }) | void |
| Camera | bridge.camera.takePhoto(options?) | BridgeMediaFile |
| Media | bridge.media.pick(options?) | BridgeMediaFile | BridgeMediaFile[] |
| Media | bridge.media.read(uri, options) | MediaReadResult |
| Media | bridge.media.upload(uri, options) | MediaUploadResult |
| Media | bridge.media.release(uri) | void |
| QR | bridge.qr.scan(options?, timeoutMs?) | QrScanResult |
| Custom | bridge.custom.request<T>(type, payload, timeoutMs?) | T |
| Custom | bridge.custom.on(type, handler) | Unsubscribe function |
| Custom | bridge.custom.ready() | void |
bridge.isAvailable() checks for the injected WebView channel or a configured iframe parent. Use ping() to test whether the host responds.
Feature options
await bridge.camera.takePhoto({ quality: 85, maxWidth: 1200 });
await bridge.media.pick({ mediaType: "image", multiple: true });
await bridge.qr.scan({ prompt: "Scan a code", cameraFacing: "back" });
await bridge.notifications.show({ title: "Hello", body: "From the mini app" });Camera options are quality, maxWidth, and maxHeight. Media pick adds mediaType: "image" | "video" | "any" and multiple. QR options are prompt, cameraFacing: "back" | "front", and formats: ["qr"].
PermissionState is "granted" | "denied" | "permanentlyDenied" | "restricted" | "limited" | "unavailable". A Contact contains phones and emails arrays and optional name fields. Coordinates contains latitude, longitude, timestamp, and optional accuracy, altitude, heading, and speed. All public types are exported from the package root.
Media lifecycle
Camera and picker results contain a host-managed uri, previewUri for immediate display, and metadata: name, mimeType, size, and kind. A multiple pick returns an array; a single pick returns one file.
const picked = await bridge.media.pick({ mediaType: "image" });
if (picked.ok) {
const file = Array.isArray(picked.data) ? picked.data[0] : picked.data;
if (file) {
// Display file.previewUri in an image element.
const uploaded = await bridge.media.upload(file.uri, {
url: "https://api.example.com/upload",
method: "POST",
fieldName: "file",
headers: { Authorization: "Bearer token" },
extraFields: { source: "mini-app" },
});
if (!uploaded.ok) console.error(uploaded.error.message);
await bridge.media.release(file.uri);
}
}To read bytes into the web app, call bridge.media.read(file.uri, { format: "base64", maxSizeMB: 5 }); format: "dataUrl" is also supported. Prefer native upload for large files. Upload supports POST, PUT, and PATCH, returning a status code and optional response body and headers. Release the URI when finished.
App-defined messages
Custom message names must begin with custom.; both sides must agree on JSON-compatible payloads and results. Register web handlers before signaling readiness:
import { bridge } from "miniapp-bridge";
const unsubscribe = bridge.custom.on("custom.theme.apply", (payload) => {
document.documentElement.dataset.theme = String(payload.theme ?? "light");
return { applied: true };
});
await bridge.custom.ready();
const session = await bridge.custom.request<{ active: boolean }>(
"custom.session.status",
{},
);
if (session.ok) console.log(session.data.active);
// Call unsubscribe() when the handler is no longer needed.The Flutter host implements web-to-host custom requests. custom.on handles host-to-web requests and returns a function that removes the handler.
React
Import hooks from miniapp-bridge/react. Every action provides run(...), loading, and the last result (initially undefined). run returns a BridgeResult.
import { useBridgeHealth, useQrScanner } from "miniapp-bridge/react";
export function NativeTools() {
const { ping, isAvailable } = useBridgeHealth();
const { scan } = useQrScanner();
return (
<div>
<button disabled={!isAvailable || ping.loading} onClick={() => void ping.run()}>
Test connection
</button>
<button disabled={scan.loading} onClick={() => void scan.run({ cameraFacing: "back" })}>
Scan QR
</button>
{scan.result?.ok && <p>{scan.result.data.rawValue}</p>}
{scan.result?.ok === false && <p>{scan.result.error.message}</p>}
</div>
);
}Available hooks: useSuperAppBridge, useBridgeHealth, useContacts, useLocation, useNotifications, useCamera, useMedia, and useQrScanner. Each accepts an optional SuperAppBridgeClient instance. useSuperAppBridge(client?) returns the client.
Flutter Web iframe
The client uses window.SuperAppBridge.postMessage when Flutter injects a WebView channel. Otherwise, in an iframe it exchanges messages with the parent using postMessage. When document.referrer is unavailable, set hostOrigin to the Flutter parent page origin:
import { SuperAppBridgeClient } from "miniapp-bridge";
export const bridge = new SuperAppBridgeClient({
hostOrigin: "https://host.example.com",
timeoutMs: 30_000,
});Pass this client to hooks, for example useBridgeHealth(bridge). The client validates incoming parent messages against hostOrigin. For sensitive data, set it explicitly and restrict embedding with CSP frame-ancestors.
The Flutter Web iframe host supports ping and custom.*. Native features such as camera, location, contacts, media, notifications, and QR return UNSUPPORTED_FEATURE there; they require a compatible mobile host.
Errors and timeouts
BridgeErrorCode includes BRIDGE_UNAVAILABLE, INVALID_REQUEST, UNSUPPORTED_FEATURE, PERMISSION_DENIED, PERMISSION_PERMANENTLY_DENIED, CANCELLED, TIMEOUT, NATIVE_ERROR, FILE_NOT_FOUND, FILE_TOO_LARGE, and UPLOAD_FAILED.
The default timeout is 30 seconds. Ping defaults to 5 seconds, QR scanning to 60 seconds, and media upload to 120 seconds. Some methods accept timeoutMs; the constructor option sets the default for other requests.
Host integration
Requests contain { id, type, payload, timeoutMs }. A mobile host responds through window.__superappBridgeHandleResponse({ id, result }), where result has the BridgeResult shape. The host provides permissions, native work, and feature support.
License
MIT
