> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mobilerun.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Your work device in the browser

> Stream a cloud device into a web app and use it from any browser.

Use a cloud device from your browser while an agent works alongside you. The server reads the stream address with the [Mobilerun SDK](https://docs.mobilerun.ai/guides/sdk-objects.md#stream-a-device-in-a-web-app); the API key never reaches the browser.

> [accordion] Set up the web app
>
> Install Node 20.19+ or 22.12+, then create a folder for the app:
>
> ```bash TypeScript theme={null}
> npm init -y
> npm pkg set type=module
> npm install @mobilerun/react @mobilerun/sdk react react-dom vite tsx
> export MOBILERUN_API_KEY="your-api-key"
> export DEVICE_ID="your-device-id"
> npx tsx server.ts
> ```
>
> ```bash Python theme={null}
> npm init -y
> npm pkg set type=module
> npm install @mobilerun/react react react-dom vite
> pip install mobilerun-sdk fastapi uvicorn
> export MOBILERUN_API_KEY="your-api-key"
> export DEVICE_ID="your-device-id"
> uvicorn server:app --host 127.0.0.1 --port 8000
> # In a second terminal in the same folder:
> npx vite --host 127.0.0.1 --port 5173 --strictPort
> ```
>
> Save the server tab you choose and `App.tsx` from one example below before running its commands. For Python, also save these two Vite files so browser API requests reach FastAPI on port 8000:
>
> ```typescript vite.config.ts theme={null}
> import { defineConfig } from 'vite';
>
> export default defineConfig({
>   server: { proxy: { '/api': 'http://127.0.0.1:8000' } },
> });
> ```
>
> ```html index.html theme={null}
> <meta name="viewport" content="width=device-width, initial-scale=1">
> <div id="root"></div>
> <script type="module" src="/App.tsx"></script>
> ```
>
> Open `http://localhost:5173`; press Ctrl+C to stop the server. The demo binds to localhost only: before exposing it, authenticate users and authorize access to each device in your backend. Never log or persist stream credentials.

## Show a device in your web app

Stream a device into a React page and tap or type directly on its screen.

**Needs:** Node 20.19+ or 22.12+ · a ready Cloud Android device · server-side API key and `DEVICE_ID` · device minutes · dev server keeps running.

> [accordion] Show the code
>
> ```typescript server.ts theme={null}
> import { MobilerunSDK } from '@mobilerun/sdk';
> import { createServer } from 'node:http';
> import { createServer as createViteServer } from 'vite';
>
> const mobilerun = new MobilerunSDK();
> const vite = await createViteServer({ server: { middlewareMode: true } });
> createServer(async (req, res) => {
>   if (req.url === '/api/stream') {
>     try {
>       const device = await mobilerun.devices.get(process.env.DEVICE_ID!);
>       res.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
>       res.end(JSON.stringify({ streamUrl: device.info?.streamUrl, streamToken: device.info?.streamToken }));
>     } catch {
>       res.writeHead(502).end('Unable to load the device');
>     }
>     return;
>   }
>   if (req.url === '/') {
>     res.writeHead(200, { 'Content-Type': 'text/html' });
>     res.end(await vite.transformIndexHtml('/', '<div id="root"></div><script type="module" src="/App.tsx"></script>'));
>     return;
>   }
>   vite.middlewares(req, res, () => res.writeHead(404).end());
> }).listen(5173, '127.0.0.1', () => console.log('Open http://localhost:5173'));
> ```
>
> ```python server.py theme={null}
> import os
> from fastapi import FastAPI
> from fastapi.responses import JSONResponse, PlainTextResponse
> from mobilerun_sdk import MobilerunSDK
>
> app = FastAPI()
> mobilerun = MobilerunSDK()
>
> @app.get("/api/stream", response_model=None)
> def stream() -> JSONResponse | PlainTextResponse:
>     try:
>         device = mobilerun.devices.get(os.environ["DEVICE_ID"])
>         info = device.info
>         return JSONResponse({
>             "streamUrl": info.stream_url if info else None,
>             "streamToken": info.stream_token if info else None,
>         }, headers={"Cache-Control": "no-store"})
>     except Exception:
>         return PlainTextResponse("Unable to load the device", status_code=502)
> ```
>
> The React component runs in the browser with either server:
>
> ```tsx App.tsx theme={null}
> import { DeviceStream, NavigationBar, type RemoteControlHandle } from '@mobilerun/react';
> import '@mobilerun/react/styles.css';
> import { useEffect, useRef, useState } from 'react';
> import { createRoot } from 'react-dom/client';
>
> function App() {
>   const controls = useRef<RemoteControlHandle>(null);
>   const [stream, setStream] = useState<{ streamUrl?: string; streamToken?: string }>({});
>   useEffect(() => { fetch('/api/stream', { cache: 'no-store' }).then(r => r.json()).then(setStream); }, []);
>   return <main style={{ fontFamily: 'sans-serif', padding: 24 }}>
>     <h1>Your work device</h1>
>     <div style={{ width: 320, height: 650, background: '#111', borderRadius: 24, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
>       <div style={{ flex: 1, minHeight: 0 }}><DeviceStream ref={controls} {...stream} hasControl muted /></div>
>       <NavigationBar onAction={action => controls.current?.sendSystemKey(action)} />
>     </div>
>   </main>;
> }
> createRoot(document.getElementById('root')!).render(<App />);
> ```

![Browser app streaming Android Settings](https://docs.mobilerun.ai/images/examples/stream-phone/show-phone.png)

Result

```text theme={null}
Tapped Settings → com.android.settings
```

## Stream your Personal Phone full-screen

Keep your Personal Phone connected through Portal and control it in a browser-sized stream.

**Needs:** Node 20.19+ or 22.12+ · a connected Personal Phone · server-side API key and its `DEVICE_ID` · Portal and the dev server keep running.

Connect your [Android device](https://docs.mobilerun.ai/guides/connect-android.md) or [iPhone](https://docs.mobilerun.ai/guides/connect-iphone.md), then use its Personal Phone ID from the dashboard. On Android, approve screen sharing when prompted. The stream fills the viewport without stretching the device image; black space may appear around it.

> [!NOTE]
>
> Online availability depends on the device, its network, and Portal remaining connected; it is not guaranteed. iPhone setup may require a connected computer. The navigation bar provides Android system keys; iPhone control and screen sharing depend on its connection mode and permissions.

> [accordion] Show the code
>
> ```typescript server.ts theme={null}
> import { MobilerunSDK } from '@mobilerun/sdk';
> import { createServer } from 'node:http';
> import { createServer as createViteServer } from 'vite';
>
> const mobilerun = new MobilerunSDK();
> const deviceId = process.env.DEVICE_ID;
> if (!deviceId) throw new Error('Set DEVICE_ID to your Personal Phone ID');
> const vite = await createViteServer({ server: { middlewareMode: true } });
> createServer(async (req, res) => {
>   if (req.url === '/api/phone' && req.method === 'GET') {
>     res.setHeader('Content-Type', 'application/json');
>     res.setHeader('Cache-Control', 'no-store');
>     try {
>       const device = await mobilerun.devices.get(deviceId);
>       const info = device.info;
>       if (info?.type !== 'device_slot') {
>         res.writeHead(400).end(JSON.stringify({ error: 'DEVICE_ID must be a Personal Phone' }));
>       } else if (device.state !== 'ready') {
>         res.end(JSON.stringify({ state: device.state }));
>       } else {
>         res.end(JSON.stringify({ state: device.state, platform: info.platform, streamUrl: info.streamUrl, streamToken: info.streamToken }));
>       }
>     } catch {
>       res.writeHead(502).end(JSON.stringify({ error: 'Unable to look up the device' }));
>     }
>     return;
>   }
>   if (req.url === '/') {
>     res.writeHead(200, { 'Content-Type': 'text/html', 'Cache-Control': 'no-store' });
>     res.end(await vite.transformIndexHtml('/', '<meta name="viewport" content="width=device-width, initial-scale=1"><div id="root"></div><script type="module" src="/App.tsx"></script>'));
>     return;
>   }
>   vite.middlewares(req, res, () => res.writeHead(404).end());
> }).listen(5173, '127.0.0.1', () => console.log('Open http://localhost:5173'));
> ```
>
> ```python server.py theme={null}
> import os
> from fastapi import FastAPI
> from fastapi.responses import JSONResponse
> from mobilerun_sdk import MobilerunSDK
>
> app = FastAPI()
> mobilerun = MobilerunSDK()
> device_id = os.environ["DEVICE_ID"]
>
> @app.get("/api/phone")
> def stream() -> JSONResponse:
>     headers = {"Cache-Control": "no-store"}
>     try:
>         device = mobilerun.devices.get(device_id)
>         info = device.info
>         if not info or info.type != "device_slot":
>             return JSONResponse({"error": "DEVICE_ID must be a Personal Phone"}, status_code=400, headers=headers)
>         if device.state != "ready":
>             return JSONResponse({"state": device.state}, headers=headers)
>         return JSONResponse({
>             "state": device.state, "platform": info.platform,
>             "streamUrl": info.stream_url, "streamToken": info.stream_token,
>         }, headers=headers)
>     except Exception:
>         return JSONResponse({"error": "Unable to look up the device"}, status_code=502, headers=headers)
> ```
>
> The React component runs in the browser with either server:
>
> ```tsx App.tsx theme={null}
> import { DeviceStream, NavigationBar, type RemoteControlHandle } from '@mobilerun/react';
> import '@mobilerun/react/styles.css';
> import { useEffect, useRef, useState } from 'react';
> import { createRoot } from 'react-dom/client';
>
> type Phone = { state: string; platform?: string; streamUrl?: string; streamToken?: string };
> function App() {
>   const controls = useRef<RemoteControlHandle>(null);
>   const [phone, setPhone] = useState<Phone>();
>   const [error, setError] = useState('');
>   const [connected, setConnected] = useState(false);
>   useEffect(() => {
>     let cancelled = false;
>     let timer: ReturnType<typeof setTimeout>;
>     async function poll() {
>       try {
>         const response = await fetch('/api/phone', { cache: 'no-store' });
>         const data = await response.json();
>         if (!response.ok) throw new Error(data.error || 'Unable to look up the device');
>         if (!cancelled) {
>           if (data.state !== 'ready' || !data.streamUrl || !data.streamToken) setConnected(false);
>           setPhone(data); setError('');
>         }
>       } catch (e) {
>         if (!cancelled) { setPhone(undefined); setConnected(false); setError(e instanceof Error ? e.message : 'Unable to look up the device'); }
>       }
>       if (!cancelled) timer = setTimeout(poll, 3000);
>     }
>     void poll();
>     return () => { cancelled = true; clearTimeout(timer); };
>   }, []);
>   const ready = phone?.state === 'ready' && phone.streamUrl && phone.streamToken;
>   const status = error || (!phone ? 'Checking device…' : phone.state !== 'ready'
>     ? 'Device offline — open Portal on the device' : !ready ? 'Waiting for stream credentials…'
>     : connected ? 'Device online' : 'Device online — connecting stream…');
>   return <main style={{ position: 'fixed', inset: 0, background: '#111', color: 'white', display: 'flex', flexDirection: 'column', fontFamily: 'sans-serif' }}>
>     <div role="status" style={{ padding: '8px 12px' }}>{status}</div>
>     <div style={{ flex: 1, minHeight: 0 }}>
>       {ready && <DeviceStream ref={controls} streamUrl={phone.streamUrl} streamToken={phone.streamToken} hasControl muted onConnectionStateChange={setConnected} />}
>     </div>
>     {ready && phone.platform === 'android' && <NavigationBar onAction={action => controls.current?.sendSystemKey(action)} />}
>   </main>;
> }
> createRoot(document.getElementById('root')!).render(<App />);
> ```

The browser polls for the device's state every three seconds. When it is not ready, the stream is removed; when it returns to `ready`, the stream mounts again with current credentials. The example never starts or stops the personal device. Before exposing this beyond localhost, authenticate users and authorize access to the device.

Result

```text theme={null}
Device offline — open Portal on the device
Device online — connecting stream…
Device online
```

## Let an agent work while you watch

Run a task on the same device, watch the agent, and stop it when you want to take over.

**Needs:** Node 20.19+ or 22.12+ · a ready Cloud Android device · server-side API key and `DEVICE_ID` · device minutes and task credits · dev server keeps running.

> [accordion] Show the code
>
> ```typescript server.ts theme={null}
> import { MobilerunSDK, WaitError, type Task } from '@mobilerun/sdk';
> import { createServer } from 'node:http';
> import { createServer as createViteServer } from 'vite';
>
> const mobilerun = new MobilerunSDK();
> const device = mobilerun.devices.fromId(process.env.DEVICE_ID!);
> const vite = await createViteServer({ server: { middlewareMode: true } });
> let current: Task | undefined;
> createServer(async (req, res) => {
>   if (req.url?.startsWith('/api/')) {
>     res.setHeader('Cache-Control', 'no-store');
>     res.setHeader('Content-Type', 'application/json');
>     try {
>       if (req.url === '/api/stream' && req.method === 'GET') {
>         const d = await mobilerun.devices.get(process.env.DEVICE_ID!);
>         res.end(JSON.stringify({ streamUrl: d.info?.streamUrl, streamToken: d.info?.streamToken }));
>       } else if (req.url === '/api/task' && req.method === 'POST') {
>         let body = '';
>         for await (const chunk of req) body += chunk;
>         const { task } = JSON.parse(body) as { task: string };
>         if (typeof task !== 'string' || !task.trim()) throw new Error('Task required');
>         const run = await device.run({ task, maxSteps: 30 });
>         current = run;
>         // Answer when the task ends. A stopped or failed task is reported, not thrown.
>         const s = await run.wait().catch(async (error) => {
>           if (error instanceof WaitError) return run.getStatus();
>           throw error;
>         });
>         res.end(JSON.stringify({ status: s.status, message: s.message, succeeded: s.succeeded }));
>       } else if (req.url === '/api/stop' && req.method === 'POST' && current) {
>         await current.stop();
>         res.end('{}');
>       } else res.writeHead(404).end('{}');
>     } catch {
>       res.writeHead(502).end(JSON.stringify({ error: 'Request failed' }));
>     }
>     return;
>   }
>   if (req.url === '/') {
>     res.writeHead(200, { 'Content-Type': 'text/html' });
>     res.end(await vite.transformIndexHtml('/', '<div id="root"></div><script type="module" src="/App.tsx"></script>'));
>     return;
>   }
>   vite.middlewares(req, res, () => res.writeHead(404).end());
> }).listen(5173, '127.0.0.1', () => console.log('Open http://localhost:5173'));
> ```
>
> ```python server.py theme={null}
> import os
> from fastapi import FastAPI, Request
> from fastapi.responses import JSONResponse
> from mobilerun_sdk import AsyncMobilerunSDK, AsyncTask, WaitError
>
> app = FastAPI()
> mobilerun = AsyncMobilerunSDK()
> device = mobilerun.devices.from_id(os.environ["DEVICE_ID"])
> current: AsyncTask | None = None
>
> @app.api_route("/api/{path:path}", methods=["GET", "POST"])
> async def api(path: str, request: Request) -> JSONResponse:
>     global current
>     headers = {"Cache-Control": "no-store"}
>     try:
>         if path == "stream" and request.method == "GET":
>             d = await mobilerun.devices.get(os.environ["DEVICE_ID"])
>             info = d.info
>             data = {"streamUrl": info.stream_url if info else None,
>                     "streamToken": info.stream_token if info else None}
>             return JSONResponse(data, headers=headers)
>         if path == "task" and request.method == "POST":
>             body = await request.json()
>             task = body.get("task")
>             if not isinstance(task, str) or not task.strip():
>                 raise ValueError("Task required")
>             run = await device.run(task=task, max_steps=30)
>             current = run
>             try:
>                 result = await run.wait()
>             except WaitError:
>                 result = await run.get_status()
>             return JSONResponse({"status": result.status, "message": result.message,
>                                  "succeeded": result.succeeded}, headers=headers)
>         if path == "stop" and request.method == "POST" and current:
>             await current.stop()
>             return JSONResponse({}, headers=headers)
>         return JSONResponse({}, status_code=404, headers=headers)
>     except Exception:
>         return JSONResponse({"error": "Request failed"}, status_code=502, headers=headers)
> ```
>
> The React component runs in the browser with either server:
>
> ```tsx App.tsx theme={null}
> import { DeviceStream, NavigationBar, type RemoteControlHandle } from '@mobilerun/react';
> import '@mobilerun/react/styles.css';
> import { useEffect, useRef, useState } from 'react';
> import { createRoot } from 'react-dom/client';
>
> function App() {
>   const controls = useRef<RemoteControlHandle>(null);
>   const [stream, setStream] = useState<{ streamUrl?: string; streamToken?: string }>({});
>   const [task, setTask] = useState('Open Settings and tell me the Android version.');
>   const [result, setResult] = useState('');
>   const [running, setRunning] = useState(false);
>   useEffect(() => { fetch('/api/stream', { cache: 'no-store' }).then(r => r.json()).then(setStream); }, []);
>   async function run() {
>     setRunning(true);
>     setResult('Running…');
>     try {
>       // The server answers when the task has ended.
>       const response = await fetch('/api/task', { method: 'POST', body: JSON.stringify({ task }) });
>       if (!response.ok) throw new Error('Could not run task');
>       setResult(JSON.stringify(await response.json(), null, 2));
>     } catch (error) { setResult(String(error)); }
>     finally { setRunning(false); }
>   }
>   return <main style={{ fontFamily: 'sans-serif', padding: 24 }}>
>     <h1>Your work device</h1>
>     <div style={{ display: 'flex', gap: 32, alignItems: 'start' }}>
>       <div style={{ width: 320, height: 650, background: '#111', borderRadius: 24, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
>         <div style={{ flex: 1, minHeight: 0 }}><DeviceStream ref={controls} {...stream} hasControl muted /></div>
>         <NavigationBar onAction={action => controls.current?.sendSystemKey(action)} />
>       </div>
>       <section style={{ width: 380 }}><h2>Run task</h2>
>         <textarea aria-label="Task" value={task} onChange={e => setTask(e.target.value)} rows={5} style={{ width: '100%' }} />
>         <p><button disabled={running} onClick={run}>Run task</button>{' '}
>         <button disabled={!running} onClick={() => fetch('/api/stop', { method: 'POST' })}>Stop agent and take over</button></p>
>         <pre style={{ whiteSpace: 'pre-wrap' }}>{result}</pre>
>       </section>
>     </div>
>   </main>;
> }
> createRoot(document.getElementById('root')!).render(<App />);
> ```

![The agent running while the device streams](https://docs.mobilerun.ai/images/examples/stream-phone/agent-running.png)

Result

```json theme={null}
{ "status": "running" }
```

![The device and the completed task result](https://docs.mobilerun.ai/images/examples/stream-phone/agent-result.png)

Result

```json theme={null}
{ "status": "completed", "message": "The Android version is 15.", "succeeded": true }
```

## Give every user their own work device

Open `http://localhost:5173/?user=alice` to find or create Alice's device, and stop it on sign-out so its apps and settings are there next time.

**Needs:** Node 20.19+ or 22.12+ · Cloud Android creation access · server-side API key · device minutes · dev server keeps running.

This query parameter only simulates sign-in: in a real app, use an authenticated identity, authorize every request, and store a durable user-to-device mapping with concurrency protection. For always-on work devices, see [device types](https://docs.mobilerun.ai/device-types.md).

> [accordion] Show the code
>
> ```typescript server.ts theme={null}
> import { MobilerunSDK, type Device } from '@mobilerun/sdk';
> import { createServer } from 'node:http';
> import { createServer as createViteServer } from 'vite';
>
> const mobilerun = new MobilerunSDK();
> const vite = await createViteServer({ server: { middlewareMode: true } });
> const pending = new Map<string, Promise<Device>>();
> async function findDevice(user: string): Promise<Device | undefined> {
>   const name = `docs-work-${user}`;
>   for await (const device of mobilerun.devices.list({ name })) {
>     if (device.name === name) return device;
>   }
> }
> async function deviceFor(user: string): Promise<Device> {
>   const existing = await findDevice(user);
>   if (existing) return await mobilerun.devices.get(existing.id); // list() omits the stream token
>   return await mobilerun.devices.create({ name: `docs-work-${user}`, deviceType: 'android_cloud_phone', billing: 'minute' });
> }
> createServer(async (req, res) => {
>   const url = new URL(req.url!, 'http://localhost');
>   if (url.pathname.startsWith('/api/')) {
>     res.setHeader('Cache-Control', 'no-store');
>     res.setHeader('Content-Type', 'application/json');
>     const user = url.searchParams.get('user') || '';
>     if (!/^[a-z0-9-]{1,32}$/.test(user)) { res.writeHead(400).end('{}'); return; }
>     try {
>       if (url.pathname === '/api/stream' && req.method === 'GET') {
>         if (!pending.has(user)) pending.set(user, deviceFor(user).finally(() => { pending.delete(user); }));
>         let device = await pending.get(user)!;
>         if (device.state === 'stopped') device = await device.resume(); // waits until ready
>         const info = device.info;
>         if (device.state !== 'ready' || !info?.streamUrl || !info.streamToken) throw new Error('Device not ready');
>         res.end(JSON.stringify({ streamUrl: info.streamUrl, streamToken: info.streamToken }));
>       } else if (url.pathname === '/api/signout' && req.method === 'POST') {
>         const device = await findDevice(user);
>         if (device && device.state !== 'stopped') await device.stop(); // waits until stopped
>         res.end('{}');
>       } else res.writeHead(404).end('{}');
>     } catch { res.writeHead(502).end(JSON.stringify({ error: 'Device unavailable' })); }
>     return;
>   }
>   if (url.pathname === '/') {
>     res.writeHead(200, { 'Content-Type': 'text/html' });
>     res.end(await vite.transformIndexHtml('/', '<div id="root"></div><script type="module" src="/App.tsx"></script>'));
>     return;
>   }
>   vite.middlewares(req, res, () => res.writeHead(404).end());
> }).listen(5173, '127.0.0.1', () => console.log('Open http://localhost:5173/?user=alice'));
> ```
>
> ```python server.py theme={null}
> import asyncio
> import re
> from fastapi import FastAPI, Request
> from fastapi.responses import JSONResponse
> from mobilerun_sdk import AsyncMobilerunSDK, AsyncDevice
>
> app = FastAPI()
> mobilerun = AsyncMobilerunSDK()
> pending: dict[str, asyncio.Task[AsyncDevice]] = {}
>
> async def find_device(user: str) -> AsyncDevice | None:
>     async for device in mobilerun.devices.list(name=f"docs-work-{user}"):
>         if device.name == f"docs-work-{user}":
>             return device
>     return None
>
> async def device_for(user: str) -> AsyncDevice:
>     try:
>         existing = await find_device(user)
>         if existing:
>             return await mobilerun.devices.get(existing.id)  # list() omits the stream token
>         return await mobilerun.devices.create(
>             name=f"docs-work-{user}", device_type="android_cloud_phone", billing="minute",
>         )  # Creating a device uses device minutes.
>     finally:
>         pending.pop(user, None)
>
> @app.api_route("/api/{path:path}", methods=["GET", "POST"])
> async def api(path: str, request: Request) -> JSONResponse:
>     headers = {"Cache-Control": "no-store"}
>     user = request.query_params.get("user", "")
>     if not re.fullmatch(r"[a-z0-9-]{1,32}", user):
>         return JSONResponse({}, status_code=400, headers=headers)
>     try:
>         if path == "stream" and request.method == "GET":
>             if user not in pending:
>                 pending[user] = asyncio.create_task(device_for(user))
>             device = await asyncio.shield(pending[user])
>             if device.state == "stopped":
>                 device = await device.resume()  # Waits until ready.
>             info = device.info
>             if device.state != "ready" or not info or not info.stream_url or not info.stream_token:
>                 raise ValueError("Device not ready")
>             return JSONResponse({"streamUrl": info.stream_url, "streamToken": info.stream_token}, headers=headers)
>         if path == "signout" and request.method == "POST":
>             device = await find_device(user)
>             if device and device.state != "stopped":
>                 await device.stop()  # Waits until stopped.
>             return JSONResponse({}, headers=headers)
>         return JSONResponse({}, status_code=404, headers=headers)
>     except Exception:
>         return JSONResponse({"error": "Device unavailable"}, status_code=502, headers=headers)
> ```
>
> The React component runs in the browser with either server:
>
> ```tsx App.tsx theme={null}
> import { DeviceStream, NavigationBar, type RemoteControlHandle } from '@mobilerun/react';
> import '@mobilerun/react/styles.css';
> import { useEffect, useRef, useState } from 'react';
> import { createRoot } from 'react-dom/client';
>
> function App() {
>   const user = new URLSearchParams(location.search).get('user') || 'alice';
>   const controls = useRef<RemoteControlHandle>(null);
>   const [stream, setStream] = useState<{ streamUrl?: string; streamToken?: string }>();
>   const [status, setStatus] = useState('Starting your device…');
>   useEffect(() => {
>     fetch(`/api/stream?user=${encodeURIComponent(user)}`, { cache: 'no-store' })
>       .then(r => { if (!r.ok) throw new Error(); return r.json(); })
>       .then(data => { setStream(data); setStatus('Your device is ready'); })
>       .catch(() => setStatus('Could not start your device'));
>   }, [user]);
>   async function signOut() {
>     setStream(undefined);
>     setStatus('Stopping your device…');
>     const response = await fetch(`/api/signout?user=${encodeURIComponent(user)}`, { method: 'POST' });
>     setStatus(response.ok ? 'Signed out' : 'Could not stop your device');
>   }
>   return <main style={{ fontFamily: 'sans-serif', padding: 24 }}>
>     <h1>{user}'s work device</h1><p>{status}</p>
>     {stream && <div style={{ width: 320, height: 650, background: '#111', borderRadius: 24, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
>       <div style={{ flex: 1, minHeight: 0 }}><DeviceStream ref={controls} {...stream} hasControl muted /></div>
>       <NavigationBar onAction={action => controls.current?.sendSystemKey(action)} />
>     </div>}
>     {stream && <p><button onClick={signOut}>Sign out</button></p>}
>   </main>;
> }
> createRoot(document.getElementById('root')!).render(<App />);
> ```

![Alice's browser device showing Display settings](https://docs.mobilerun.ai/images/examples/stream-phone/user-phone.png)

Result

```text theme={null}
Signed out → stopped
Signed in again → ready; Dark theme still on
```

## Run it on many devices

> [!TIP]
>
> Stream as many devices as you need: one tile per device.

Put several ready devices in a browser grid and control each one independently.

**Needs:** Node 20.19+ or 22.12+ · ready Cloud Android devices · server-side API key and comma-separated `DEVICE_IDS` · device minutes per device · dev server keeps running.

Set `DEVICE_IDS` to your device IDs before starting the server:

```bash theme={null}
export DEVICE_IDS="first-device-id,second-device-id"
```

> [accordion] Show the code
>
> ```typescript server.ts theme={null}
> import { MobilerunSDK } from '@mobilerun/sdk';
> import { createServer } from 'node:http';
> import { createServer as createViteServer } from 'vite';
>
> const mobilerun = new MobilerunSDK();
> const ids = (process.env.DEVICE_IDS || '').split(',').map(id => id.trim()).filter(Boolean);
> const vite = await createViteServer({ server: { middlewareMode: true } });
> createServer(async (req, res) => {
>   if (req.url === '/api/streams') {
>     try {
>       const devices = await Promise.all(ids.map(id => mobilerun.devices.get(id)));
>       res.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
>       res.end(JSON.stringify(devices.map(d => ({ id: d.id, streamUrl: d.info?.streamUrl, streamToken: d.info?.streamToken }))));
>     } catch { res.writeHead(502).end('Unable to load devices'); }
>     return;
>   }
>   if (req.url === '/') {
>     res.writeHead(200, { 'Content-Type': 'text/html' });
>     res.end(await vite.transformIndexHtml('/', '<div id="root"></div><script type="module" src="/App.tsx"></script>'));
>     return;
>   }
>   vite.middlewares(req, res, () => res.writeHead(404).end());
> }).listen(5173, '127.0.0.1', () => console.log('Open http://localhost:5173'));
> ```
>
> ```python server.py theme={null}
> import os
> from fastapi import FastAPI
> from fastapi.responses import JSONResponse, PlainTextResponse
> from mobilerun_sdk import MobilerunSDK
>
> app = FastAPI()
> mobilerun = MobilerunSDK()
> ids = [value.strip() for value in os.environ.get("DEVICE_IDS", "").split(",") if value.strip()]
>
> @app.get("/api/streams", response_model=None)
> def streams() -> JSONResponse | PlainTextResponse:
>     try:
>         devices = [mobilerun.devices.get(device_id) for device_id in ids]
>         return JSONResponse([{
>             "id": device.id,
>             "streamUrl": device.info.stream_url if device.info else None,
>             "streamToken": device.info.stream_token if device.info else None,
>         } for device in devices], headers={"Cache-Control": "no-store"})
>     except Exception:
>         return PlainTextResponse("Unable to load devices", status_code=502)
> ```
>
> The React component runs in the browser with either server:
>
> ```tsx App.tsx theme={null}
> import { DeviceStream, NavigationBar, type RemoteControlHandle } from '@mobilerun/react';
> import '@mobilerun/react/styles.css';
> import { useEffect, useRef, useState } from 'react';
> import { createRoot } from 'react-dom/client';
>
> type Phone = { id: string; streamUrl?: string; streamToken?: string };
> function Tile({ phone, number }: { phone: Phone; number: number }) {
>   const controls = useRef<RemoteControlHandle>(null);
>   return <section><h2>Device {number}</h2>
>     <div style={{ width: 280, height: 570, background: '#111', borderRadius: 24, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
>       <div style={{ flex: 1, minHeight: 0 }}><DeviceStream ref={controls} streamUrl={phone.streamUrl} streamToken={phone.streamToken} hasControl muted /></div>
>       <NavigationBar onAction={action => controls.current?.sendSystemKey(action)} />
>     </div>
>   </section>;
> }
> function App() {
>   const [phones, setPhones] = useState<Phone[]>([]);
>   useEffect(() => { fetch('/api/streams', { cache: 'no-store' }).then(r => r.json()).then(setPhones); }, []);
>   return <main style={{ fontFamily: 'sans-serif', padding: 24 }}><h1>Your device wall</h1>
>     <div style={{ display: 'flex', flexWrap: 'wrap', gap: 24 }}>{phones.map((phone, i) => <Tile key={phone.id} phone={phone} number={i + 1} />)}</div>
>   </main>;
> }
> createRoot(document.getElementById('root')!).render(<App />);
> ```

![Two live Android devices in a browser grid](https://docs.mobilerun.ai/images/examples/stream-phone/phone-wall.png)

Result

```text theme={null}
Device 1: live
Device 2: live
```

> [accordion] For AI agents
>
> Build a local React app that streams an authorized Mobilerun device using `@mobilerun/react`. Keep the API key on the server, return only device-scoped stream credentials with `Cache-Control: no-store`, and use `DeviceStream` with `NavigationBar`. For multiple users, authenticate and authorize every request and maintain a durable user-to-device mapping; never log stream credentials.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.