Skip to content

Commit 7898b02

Browse files
committed
update code examples
1 parent b6accfa commit 7898b02

File tree

2 files changed

+105
-50
lines changed

2 files changed

+105
-50
lines changed

src/content/docs/sandbox/api/ports.mdx

Lines changed: 55 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -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
4546
await sandbox.startProcess('npm run dev');
4647
const 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
5557
await 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
7978
const { ports } = await sandbox.getExposedPorts();
8079
8180
for (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
9292
import { connect } from '@cloudflare/sandbox';
9393
9494
const 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

108117
export 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+
```

src/content/docs/sandbox/index.mdx

Lines changed: 50 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -114,29 +114,55 @@ df['sales'].sum() # Last expression is automatically returned
114114
</TabItem>
115115
<TabItem label="WebSocket Connections">
116116
```typescript
117-
import { getSandbox, connect } from '@cloudflare/sandbox';
118-
119-
export default {
120-
async fetch(request: Request, env: Env): Promise<Response> {
121-
const sandbox = getSandbox(env.Sandbox, 'user-123');
122-
123-
// Start a WebSocket echo server
124-
const serverCode = `
125-
Bun.serve({
126-
port: 8080,
127-
fetch(req, server) { if (server.upgrade(req)) return; },
128-
websocket: { message(ws, msg) { ws.send(\`Echo: \${msg}\`); } }
129-
});
130-
`;
131-
await sandbox.writeFile('/workspace/server.js', serverCode);
132-
await sandbox.startProcess('bun /workspace/server.js');
133-
134-
// Route WebSocket connections to the server
135-
return await connect(sandbox, request, 8080);
136-
}
137-
};
138-
```
139-
</TabItem>
117+
import { getSandbox, connect, type Sandbox } from "@cloudflare/sandbox";
118+
119+
export { Sandbox } from "@cloudflare/sandbox";
120+
121+
type Env = {
122+
Sandbox: DurableObjectNamespace<Sandbox>;
123+
};
124+
125+
const initialized = new Set<string>();
126+
127+
export default {
128+
async fetch(request: Request, env: Env): Promise<Response> {
129+
const sandboxId = "my-sandbox";
130+
const sandbox = getSandbox(env.Sandbox, sandboxId);
131+
132+
if (request.headers.get('Upgrade')?.toLowerCase() === 'websocket') {
133+
// Initialize WebSocket server on first connection
134+
if (!initialized.has(sandboxId)) {
135+
const serverCode = `
136+
137+
Bun.serve({
138+
port: 8080,
139+
fetch(req, server) {
140+
if (server.upgrade(req)) return;
141+
return new Response('WebSocket server', { status: 200 });
142+
},
143+
websocket: {
144+
message(ws, msg) {
145+
ws.send(\`Echo: \${msg}\`);
146+
}
147+
}
148+
});
149+
`;
150+
await sandbox.writeFile('/workspace/server.js', serverCode);
151+
await sandbox.startProcess('bun /workspace/server.js');
152+
await new Promise(resolve => setTimeout(resolve, 1000));
153+
initialized.add(sandboxId);
154+
}
155+
156+
return await connect(sandbox, request, 8080);
157+
}
158+
159+
return new Response('WebSocket endpoint. Connect using ws:// protocol.', { status: 200 });
160+
161+
},
162+
};
163+
164+
```
165+
</TabItem>
140166

141167
</Tabs>
142168

@@ -294,3 +320,4 @@ Stateful coordination layer that enables Sandbox to maintain persistent environm
294320
</LinkTitleCard>
295321

296322
</CardGrid>
323+
```

0 commit comments

Comments
 (0)