Quickstart: Connected Mode
View as MarkdownBy the end of this page:
- your Next.js app serves the Uncage hub at
/api/uncage; - a page shows
<AgentChat>, which first offers “Connect your computer”; /deviceis where users approve their computer;- Claude Code on the user’s computer can call one of your tools,
save_note, which runs in your server as that user.
You play both roles: the website developer, then the user who connects a computer.
Copy prompt for your coding agent
Section titled “Copy prompt for your coding agent”If you use Claude Code, Codex or another coding agent, paste this into it instead of following the steps by hand:
Add Uncage Connected Mode to this Next.js (App Router) app, following https://uncage-dev.vercel.app/docs/start/quickstart-connected.md exactly.Read https://uncage-dev.vercel.app/docs/skills/uncage/SKILL.md first and follow its rules.1. Install @uncage/hub, @uncage/react-ui and zod.2. Create lib/auth.ts, lib/tools.ts, lib/uncage-hub.ts, lib/hub-registry.ts, server.ts, app/uncage/page.tsx, app/device/page.tsx, app/device/actions.ts, app/device/approve-page.tsx and the headers in next.config.ts, as on that page.3. Wire lib/auth.ts to this app's existing sign-in (find how the app reads the current user). Do not keep the development user unless the app has no sign-in at all.4. Change the "dev" and "start" scripts to run server.ts with node (Node.js 22.18 or newer), set "type": "module" in package.json and "allowImportingTsExtensions": true in tsconfig.json.5. Add .uncage-hub/ to .gitignore.Verify: start the dev server, then curl -s http://localhost:3000/api/uncage/install.sh | head -3 prints the installer, and curl -sI http://localhost:3000/device shows the headers Content-Security-Policy: frame-ancestors 'none' and X-Frame-Options: DENY (no ?code=: unknown codes count as failed guesses and are rate limited). Report what you changed and anything you could not wire.Before you start
Section titled “Before you start”- Website side: a Next.js 16 app (App Router) that you run with Node. Node.js 22.18 or newer, because the custom server below is a
.tsfile that Node runs directly. Starting fresh:npx create-next-app@latest my-site(TypeScript, App Router). - User side (your own computer for this test): Node.js 22+ (the installer below can set it up), and Claude Code installed and signed in:
npm i -g @anthropic-ai/claude-code, then runclaudeonce and type/login. macOS, Linux or Windows (macOS is verified on a real device; Linux and Windows are CI verified, awaiting real-device confirmation).
1. Install
Section titled “1. Install”npm i @uncage/hub @uncage/react-ui zod2. Who is signed in
Section titled “2. Who is signed in”The hub asks your app who the user is, on every browser request. For this quickstart, use a fixed development user. The auth guide shows how to connect a real sign-in.
import type { HubUser } from '@uncage/hub';
/** * Replace both functions with your real sign-in before you deploy. * `userFromRequest` is used by the hub (a Fetch `Request`); `currentUser` by your pages. */export async function userFromRequest(_req: Request): Promise<HubUser | null> { return developmentUser();}
export async function currentUser(): Promise<HubUser | null> { return developmentUser();}
function developmentUser(): HubUser { if (process.env.NODE_ENV === 'production') { throw new Error('lib/auth.ts still returns the development user: connect it to your sign-in.'); } return { id: 'dev-user', name: 'Developer' };}3. Define a tool
Section titled “3. Define a tool”A site tool is a capability of your website that Claude Code can call. Its handler runs in your server, as the user who owns the session. The user’s computer only receives the name, the description and the JSON Schema generated from input.
import { defineTool, type SiteTool } from '@uncage/hub';import { z } from 'zod';
/** Stand-in for your database. */// Kept on globalThis: server.ts and Next.js pages load separate copies of this module,// so a plain module-level Map would look empty from a page that lists the notes.type Notes = Map<string, Array<{ id: string; title: string; text: string }>>;const g = globalThis as typeof globalThis & { __demoNotes?: Notes };const notes: Notes = (g.__demoNotes ??= new Map());
export const saveNote = defineTool({ name: 'save_note', description: 'Save a note to the signed-in user’s notes on the website. Returns the note id.', input: z.object({ title: z.string().min(1).max(120), text: z.string().min(1).max(10_000), }), handler: async ({ title, text }, ctx) => { const mine = notes.get(ctx.user.id) ?? []; const note = { id: `note_${mine.length + 1}`, title, text }; notes.set(ctx.user.id, [...mine, note]); return { saved: note.id }; },});
export const tools: SiteTool[] = [saveNote];4. Create the hub
Section titled “4. Create the hub”The hub is created once, by your custom server. Your pages need it too (the approval page calls it), but Next.js bundles page code separately, so the server hands the instance over through globalThis.
import { createHub, type Hub } from '@uncage/hub';import { pgliteHubStore } from '@uncage/hub/node';import { userFromRequest } from './auth.ts';import { tools } from './tools.ts';
export async function createAppHub(): Promise<Hub> { return createHub({ // The URL your users open. Also what `uncage setup <url>` is given. publicUrl: process.env.PUBLIC_URL ?? 'http://localhost:3000', getUser: userFromRequest, // The hub's own database: embedded Postgres in this folder (computers, sessions, tool calls). store: await pgliteHubStore({ dataDir: './.uncage-hub' }), tools, // Keep a copy of every conversation on the website (readable while the computer is off). sessionStorage: 'site', });}import type { Hub } from '@uncage/hub';
const KEY = Symbol.for('my-site.uncage-hub');
/** Called once by server.ts. */export function publishHub(hub: Hub): void { (globalThis as Record<symbol, unknown>)[KEY] = hub;}
/** The hub server.ts created, for pages and Server Actions. */export function getHub(): Hub { const hub = (globalThis as Record<symbol, unknown>)[KEY] as Hub | undefined; if (!hub) throw new Error('The Uncage hub is not running: start the app with `node server.ts`, not `next dev`.'); return hub;}pgliteHubStore keeps the hub’s data in ./.uncage-hub (embedded PGlite, one process per folder). Add that folder to .gitignore, and keep it on a persistent disk when you deploy.
5. The custom server
Section titled “5. The custom server”One Node HTTP server carries everything: the hub’s HTTP API under /api/uncage, the computers’ WebSockets at /api/uncage/agent, and the Next.js app for every other path. toNodeHandler and attachWebSocket come from @uncage/hub/node, the Node-only part of the hub.
import { createServer } from 'node:http';import { attachWebSocket, toNodeHandler } from '@uncage/hub/node';import next from 'next';import { publishHub } from './lib/hub-registry.ts';import { createAppHub } from './lib/uncage-hub.ts';
const dev = process.env.NODE_ENV !== 'production';// If you change PORT, also set PUBLIC_URL (lib/uncage-hub.ts) to the URL users open.const port = Number(process.env.PORT ?? 3000);
const hub = await createAppHub();publishHub(hub);const hubHandler = toNodeHandler(hub);
const server = createServer();const app = next({ dev, hostname: 'localhost', port, httpServer: server });const handle = app.getRequestHandler();await app.prepare();
server.on('request', (req, res) => { // Paths under /api/uncage go to the hub; everything else falls through to Next.js. hubHandler(req, res, () => void handle(req, res));});
attachWebSocket(hub, server); // computers connect to ws(s)://<host>/api/uncage/agent
if (dev) { // Next.js hot reload uses WebSockets too; leave the hub's path to the hub. const upgrade = app.getUpgradeHandler(); server.on('upgrade', (req, socket, head) => { if ((req.url ?? '').split('?')[0] !== `${hub.basePath}/agent`) void upgrade(req, socket, head); });}
server.on('error', (err: NodeJS.ErrnoException) => { // Exit (and release ./.uncage-hub) instead of lingering when the port is taken. if (err.code === 'EADDRINUSE') console.error(`Port ${port} is in use: set PORT (and PUBLIC_URL).`); else console.error(err); process.exit(1);});
server.listen(port, () => console.log(`ready on http://localhost:${port}`));Run it with Node instead of next dev. Node runs server.ts directly (it strips the types), and the files it imports use explicit .ts extensions, so:
{ "type": "module", "scripts": { "dev": "node server.ts", "build": "next build", "start": "NODE_ENV=production node server.ts" }}{ "compilerOptions": { "allowImportingTsExtensions": true }}6. The chat page
Section titled “6. The chat page”<AgentChat> talks to /api/uncage by default. It notices that this is a hub (not a local daemon) and switches to Connected Mode by itself: with no computer yet, it shows <ConnectMachine> with the one-command installer; afterwards, the header shows which computer the conversation runs on.
'use client';import { AgentChat, UncageProvider } from '@uncage/react-ui';import '@uncage/react-ui/styles.css';
export default function UncagePage() { return ( <div style={{ height: '100vh' }}> <UncageProvider> <AgentChat starterPrompts={['Write a short poem about this website and save it with save_note']} /> </UncageProvider> </div> );}7. The approval page
Section titled “7. The approval page”uncage setup sends the user to /device?code=… on your site. Approving there gives that computer access to the user’s account, so the page must be served only to the signed-in user, must not be framable, and must record the decision with a POST that only your own origin can send. Next.js Server Actions are POST-only and check the Origin, which covers the last point. A code from the link is never trusted on its own: <ApproveDevice> shows the request time and IP and asks for the code’s last 4 characters (phishing links).
import type { ApproveDeviceProps } from '@uncage/react-ui';import { currentUser } from '../../lib/auth.ts';import { getHub } from '../../lib/hub-registry.ts';import { ApprovePage } from './approve-page.tsx';
export const dynamic = 'force-dynamic';
type DeviceError = NonNullable<ApproveDeviceProps['error']>;
export default async function DevicePage({ searchParams }: { searchParams: Promise<{ code?: string }> }) { const { code = '' } = await searchParams; const user = await currentUser(); if (!user) return <p>Sign in first, then open this link again.</p>; // or redirect to your login page let lookup: ApproveDeviceProps['lookup'] = null; let error: DeviceError | undefined; try { lookup = code ? await getHub().lookupDevice(code, user) : null; } catch (e) { // Unknown codes count as failed guesses; after 10 in 10 minutes lookupDevice throws `rate_limited`. // <ApproveDevice> shows the error, localized, in place of "code not found". const err = e as { code?: string; message?: string }; error = { code: err.code === 'rate_limited' ? 'rate_limited' : 'internal_error', message: err.message ?? 'Could not check this code.' }; } return <ApprovePage code={code} lookup={lookup} initialError={error} />;}'use server';import { currentUser } from '../../lib/auth.ts';import { getHub } from '../../lib/hub-registry.ts';
export type DecideResult = { result: 'ok' | 'not_found' | 'expired' } | { error: { code: string; message: string } };
/** A Server Action: a POST that Next.js only accepts from this site's own Origin. */export async function decide(code: string, approve: boolean): Promise<DecideResult> { const user = await currentUser(); if (!user) return { error: { code: 'unauthorized', message: 'Sign in again.' } }; try { const hub = getHub(); return { result: await (approve ? hub.approveDevice(code, user) : hub.denyDevice(code, user)) }; } catch (e) { const err = e as { code?: string; message?: string }; return { error: { code: err.code ?? 'internal_error', message: err.message ?? 'Failed' } }; }}'use client';import { ApproveDevice, type ApproveDeviceProps, type ApproveDeviceState } from '@uncage/react-ui';import '@uncage/react-ui/styles.css';import { useState } from 'react';import { decide } from './actions.ts';
export function ApprovePage({ code, lookup, initialError,}: Pick<ApproveDeviceProps, 'code' | 'lookup'> & { initialError?: ApproveDeviceProps['error'] }) { const [state, setState] = useState<ApproveDeviceState>('idle'); const [error, setError] = useState<ApproveDeviceProps['error']>(initialError); const act = async (approve: boolean) => { setState(approve ? 'approving' : 'denying'); setError(undefined); const r = await decide(code, approve); if ('error' in r) { setState('idle'); // the buttons stay enabled for a retry setError(r.error as ApproveDeviceProps['error']); } else { setState(r.result === 'ok' ? (approve ? 'approved' : 'denied') : r.result); } }; return <ApproveDevice code={code} lookup={lookup} state={state} error={error} onApprove={() => void act(true)} onDeny={() => void act(false)} />;}Refuse framing for the approval page (and, simplest, for every page):
import type { NextConfig } from 'next';
const config: NextConfig = { async headers() { return [ { source: '/:path*', headers: [ { key: 'Content-Security-Policy', value: "frame-ancestors 'none'" }, { key: 'X-Frame-Options', value: 'DENY' }, ], }, ]; },};
export default config;8. Run the website
Section titled “8. Run the website”npm run devCheck the hub answers:
curl -s http://localhost:3000/api/uncage/install.sh | head -3It prints the start of the installer (#!/usr/bin/env bash, # Uncage installer: …).
9. Connect your computer (the user’s side)
Section titled “9. Connect your computer (the user’s side)”Open http://localhost:3000/uncage. The chat shows Connect your computer with one command, on the tab of your operating system. On a real deployment the user copies it. For this local test:
-
Run the command. On macOS or Linux,
curl -fsSL http://localhost:3000/api/uncage/install.sh | bash; on Windows (PowerShell),irm http://localhost:3000/api/uncage/install.ps1 | iex. The installer checks the computer first (Node.js 22+, npm, a coding agent), asks[Y/n]before each step it needs (using your Node version manager if you have one; neversudoor admin rights), installs@uncage/cli, and offers to rununcage setup http://localhost:3000for you: answer Y. See Install on your computer for what it does on each OS. -
Already have the CLI (
npm i -g @uncage/cli)? Run the setup command the page shows under Already have the CLI? instead:Terminal window uncage setup http://localhost:3000 -
Approve. Setup prints a code and opens
http://localhost:3000/device?code=…. The page warns you never to approve a code someone sent you, and hides the code’s last 4 characters: type them from the terminal, then click Approve. Setup saves the machine token in~/.uncage/agent.yamland starts the background agent (a per-user service: launchd on macOS, systemd on Linux, a scheduled task on Windows;uncage agent statusshows it).
Back on the chat page, the status changes from “Waiting for your computer…” to Connected: <your computer’s name>.
10. Send a task
Section titled “10. Send a task”Click the starter prompt, or type: “Write a short poem about this website and save it with save_note”.
- Claude Code runs on your computer, in
~/Uncage/localhost-3000/<session id>/. - It calls
mcp__site__save_note. The handler runs in your Next.js server asdev-user. - The answer streams into the chat. Commands and file edits show approval cards with Allow once / Deny.
Stop the agent (uncage agent uninstall, or quit uncage agent if you ran it in the foreground) and reload the page: the conversation is still there (the URL keeps ?session=…; it is also in the sidebar), because of sessionStorage: 'site', and the composer says the computer is offline.
What you built
Section titled “What you built”| File | Role |
|---|---|
lib/auth.ts |
Who is signed in (replace with your auth) |
lib/tools.ts |
Your site tools |
lib/uncage-hub.ts, lib/hub-registry.ts |
Creating the hub, sharing it with pages |
server.ts |
One HTTP server: hub API, computer WebSockets, Next.js |
app/uncage/page.tsx |
The chat |
app/device/*, next.config.ts |
The approval page, safely |
The repository’s examples/connected-demo is the same setup, grown into a full site: sign-in, two tools that create and publish a landing page (pulling the files from the user’s computer), a skill, an assets gallery, and a two-node mode with Redis and Postgres. It is tested end to end against real Claude Code.
- Define tools: validation, errors, confirmation, the file channel.
- Write skills and choose them per run.
- Auth and device approval: connect your real sign-in.
- Deploy: put it on a server (traditional mode), or move to Vercel (FaaS mode).
- Multi-node: Postgres + Redis behind a load balancer.
- Before you deploy behind a proxy: set the client IP (
trust proxyorrateLimits.clientIp), or every user shares oneuncage setuprate-limit bucket. See behind a proxy.