@@ -24,6 +24,7 @@ const response = await sandbox.exposePort(port: number, options?: ExposePortOpti
2424```
2525
2626** Parameters** :
27+
2728- ` port ` - Port number to expose (1024-65535)
2829- ` options ` (optional):
2930 - ` name ` - Friendly name for the port
@@ -44,7 +45,8 @@ const api = await sandbox.exposePort(3000, { name: 'api' });
4445
4546await sandbox.startProcess('npm run dev');
4647const frontend = await sandbox.exposePort(5173, { name: 'frontend' });
47- ```
48+
49+ ````
4850</TypeScriptExample>
4951
5052### `unexposePort()`
@@ -53,16 +55,13 @@ Remove an exposed port and close its preview URL.
5355
5456```ts
5557await sandbox.unexposePort(port: number): Promise<void>
56- ```
58+ ````
5759
5860**Parameters**:
61+
5962- `port` - Port number to unexpose
6063
61- <TypeScriptExample >
62- ```
63- await sandbox.unexposePort(8000);
64- ```
65- </TypeScriptExample >
64+ <TypeScriptExample>``` await sandbox.unexposePort(8000); ```</TypeScriptExample>
6665
6766### `getExposedPorts()`
6867
@@ -79,9 +78,10 @@ const response = await sandbox.getExposedPorts(): Promise<GetExposedPortsRespons
7978const { ports } = await sandbox.getExposedPorts();
8079
8180for (const port of ports) {
82- console.log(`${port.name || port.port}: ${port.exposedAt}`);
81+ console.log(`${port.name || port.port}: ${port.exposedAt}`);
8382}
84- ```
83+
84+ ````
8585</TypeScriptExample>
8686
8787### `connect()`
@@ -92,9 +92,10 @@ Route incoming WebSocket upgrade requests to WebSocket servers running in the sa
9292import { connect } from '@cloudflare/sandbox';
9393
9494const response = await connect(sandbox: Sandbox, request: Request, port: number): Promise<Response>
95- ```
95+ ````
9696
9797**Parameters**:
98+
9899- `sandbox` - Sandbox instance containing the WebSocket server
99100- `request` - Incoming WebSocket upgrade request
100101- `port` - Port number (1024-65535, excluding 3000)
@@ -103,31 +104,58 @@ const response = await connect(sandbox: Sandbox, request: Request, port: number)
103104
104105<TypeScriptExample>
105106```
106- import { getSandbox, connect } from '@cloudflare/sandbox';
107+ import { getSandbox , connect , type Sandbox } from " @cloudflare/sandbox" ;
108+
109+ export { Sandbox } from " @cloudflare/sandbox" ;
110+
111+ type Env = {
112+ Sandbox : DurableObjectNamespace < Sandbox > ;
113+ } ;
114+
115+ const initialized = new Set<string >();
107116
108117export default {
109118 async fetch(request : Request , env : Env ): Promise <Response > {
110- const sandbox = getSandbox(env.Sandbox, 'my-sandbox');
111-
112- // Start WebSocket echo server
113- const serverCode = `
114- Bun.serve({
115- port: 8080,
116- fetch(req, server) { if (server.upgrade(req)) return; },
117- websocket: { message(ws, msg) { ws.send(\`Echo: \${msg}\`); } }
118- });
119- `;
120- await sandbox.writeFile('/workspace/server.js', serverCode);
121- await sandbox.startProcess('bun /workspace/server.js');
122-
123- // Route WebSocket connections
124- return await connect(sandbox, request, 8080);
125- }
119+ const sandboxId = " my-sandbox" ;
120+ const sandbox = getSandbox (env .Sandbox , sandboxId );
121+
122+ if (request .headers .get (' Upgrade' )?.toLowerCase () === ' websocket' ) {
123+ // Initialize WebSocket server on first connection
124+ if (! initialized .has (sandboxId )) {
125+ const serverCode = `
126+
127+ Bun.serve({
128+ port: 8080,
129+ fetch(req, server) {
130+ if (server.upgrade(req)) return;
131+ return new Response('WebSocket server', { status: 200 });
132+ },
133+ websocket: {
134+ message(ws, msg) {
135+ ws.send(\` Echo: \$ {msg}\` );
136+ }
137+ }
138+ });
139+ ` ;
140+ await sandbox .writeFile (' /workspace/server.js' , serverCode );
141+ await sandbox .startProcess (' bun /workspace/server.js' );
142+ await new Promise (resolve => setTimeout (resolve , 1000 ));
143+ initialized .add (sandboxId );
144+ }
145+
146+ return await connect (sandbox , request , 8080 );
147+ }
148+
149+ return new Response (' WebSocket endpoint. Connect using ws:// protocol.' , { status: 200 });
150+
151+ },
126152};
153+
127154```
128155</TypeScriptExample>
129156
130157## Related resources
131158
132159- [Preview URLs concept](/sandbox/concepts/preview-urls/) - How preview URLs work
133160- [Commands API](/sandbox/api/commands/) - Start background processes
161+ ```
0 commit comments