React components for embedding Mobilerun's native streaming.
Live WebRTC video + full scrcpy remote control of a cloud device, in any React app.
Building Mobilerun phones into your platform? Start with the Partner guide. It walks through the API key, one phone per user, stream tokens and live viewing step by step.
|
In this package
Lower-level hooks and scrcpy helpers: see docs/. Requirements
|
npm install @mobilerun/react @mobilerun/sdk react react-domreact, react-dom and @mobilerun/sdk are peer dependencies.
- Your server mints a short-lived stream token for one device with your API key
using
client.streamTokens.createfrom@mobilerun/sdk6.3.0+. Follow the Partner guide. - Your app's
tokenProviderasks your server for a stream token before each connection. - The SDK opens the stream with that token, one token per connection, and reconnects with a fresh one.
Use this Node backend helper with @mobilerun/sdk 6.3.0 or later. It reads
MOBILERUN_API_KEY on the server;
see Stream tokens for route setup, metadata fetching and error handling.
import { MobilerunSDK } from '@mobilerun/sdk';
const client = new MobilerunSDK({ logLevel: 'off' }); // reads MOBILERUN_API_KEY on the Node server
export async function mintStreamToken(deviceId: string): Promise<Response> {
// Authenticate your user and check they own the device before minting.
const { key, keyId, expiresAt } = await client.streamTokens.create({
deviceId,
ttlSeconds: 120,
allowedOrigins: ['https://partner.example'], // replace with your browser app's origin
}, { maxRetries: 0 });
return Response.json({ key, keyId, expiresAt }, { status: 201, headers: { 'Cache-Control': 'no-store' } });
}REST fallback: POST /v1/identity/stream-keys with the same body and your server-held API key.
Revoke a token on the server with await client.streamTokens.delete(keyId).
Pass a stream URL fetched through your backend and a callback that calls your mint route:
import { DeviceStream } from '@mobilerun/react';
import '@mobilerun/react/styles.css';
export function DevicePanel({ deviceId, streamUrl }: { deviceId: string; streamUrl: string }) {
const tokenProvider = async () => {
const res = await fetch(`/api/v1/devices/${encodeURIComponent(deviceId)}/stream-key`, { method: 'POST', cache: 'no-store' });
if (!res.ok) throw new Error('Stream token request failed');
return (await res.json()).key;
};
return <div style={{ width: 360, height: 780 }}><DeviceStream streamUrl={streamUrl} tokenProvider={tokenProvider} hasControl /></div>;
}Never log or cache stream tokens. Your backend must authenticate callers and authorize the device.
The full example also shows useDeviceStream and device token (legacy) compatibility.
tokenProvider runs before every connection attempt, the first one and each reconnect, and the SDK
never reuses a token it returns. Use it: stream tokens are single-use, so only a provider can reconnect.
The legacy streamToken prop (device token) is deprecated and an explicit exception to that rule: it is kept until the
device token (legacy) is removed, and the SDK passes the same value again on every reconnect. A single-use stream token
given this way is rejected on the second attempt, so the stream ends in the Retry state
(connection_refused). The component logs one console warning per mount.
React to failures and white-label the texts:
<DeviceStream
streamUrl={streamUrl}
tokenProvider={tokenProvider}
hasControl
onError={({ reason, attempt, final }) => report(reason, attempt, final)}
labels={{ connecting: 'Starting…', disconnected: 'Reconnecting', unavailable: 'Phone unavailable', retry: 'Try again' }}
/>reason is credentials_unavailable (your provider threw or took longer than 10 s),
connection_refused (the socket closed before it opened: a used, expired or wrong stream token, a wrong
device or a refused origin; browsers cannot see the HTTP status), disconnected (an open session
dropped, including the 30-minute server cap) or unknown. final: true means retries stopped and
the Retry button is showing. labels replaces every text the component renders.
Pass your backend's per-device publishCapabilities snapshot to enable microphone injection
(and camera injection when supported). A floating pill over the stream provides both toggles;
active inputs show red. Set hidePublishControls for your own controls and use a
DeviceStreamHandle ref's startPublish({ audio: true, video: true }), stopPublish() and
getPublishState(). Audio is required; the SDK never silently starts a video-only session.
onPublishStateChange observes this separate state. Publish errors carry operation: 'publish'
in onError; an explicit server forbidden maps to publish_not_allowed, while a silent server
maps to publish_unsupported after 5 seconds. Permission prompts happen only after the device accepts an explicit start; the 30-second active
window includes the prompt. Refused or silent requests never capture.
Stopping or reconnecting releases capture; publication never resumes automatically.
See Publishing inputs
for capabilities, permissions, ref types and labels.
The stylesheet defines no unprefixed CSS variable, so it cannot clash with your own --background. Set
these on any ancestor of the component or on its root (.mobilerun-device-stream):
--mr-background, --mr-foreground, --mr-card, --mr-card-foreground, --mr-muted,
--mr-muted-foreground, --mr-border, --mr-ring, --mr-primary, --mr-primary-foreground,
--mr-accent, --mr-accent-foreground, --mr-destructive.
Each color resolves in this order: --mr-<name>, then the old unprefixed --<name> (kept for one more
minor release, so a host theme that already defines --background keeps working), then the bundled
default. Add .dark to an ancestor, or to the component root, for the bundled dark defaults.
.mobilerun-device-stream { --mr-primary: oklch(0.55 0.18 268); --mr-background: oklch(0.985 0.004 85); }Coding agents: Mobilerun device stream skill.
| Guide | Covers |
|---|---|
| Stream tokens | Server routes, device metadata, tokenProvider, retries and device tokens (legacy). |
| Components and styling | Components, prebuilt CSS, theme variables and dark mode. |
| Task approvals | Webhooks, backend decisions, cards, bottom sheets and labels. |
See CONTRIBUTING.md for builds, tests, conformance fixtures and the example app. Report vulnerabilities privately as described in SECURITY.md.
