Skip to content

Commit c8bcdfc

Browse files
use sessions
1 parent 527060f commit c8bcdfc

10 files changed

Lines changed: 166 additions & 137 deletions

File tree

packages/projects-docs/pages/sdk/_meta.json

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
"title": "Sandboxes"
1414
},
1515
"create-resume": "Create & Resume",
16-
"sessions-clients": "Sessions & Clients",
16+
"sessions": "Sessions",
1717
"preview-tokens": "Preview Tokens",
1818
"hibernate": "Hibernate",
1919
"fork": "Fork",
@@ -22,19 +22,20 @@
2222
"persistence": "Persistence",
2323
"update-sandbox": "Update Sandbox",
2424

25-
"-- connect-reference": {
25+
"-- websocket-sessions": {
2626
"type": "separator",
27-
"title": "Connect"
27+
"title": "WebSocket Sessions"
2828
},
2929
"connect": "Connect",
30+
"browser": "Connect Browser",
3031
"filesystem": "File System",
3132
"shells": "Shells",
3233
"ports": "Ports",
3334
"tasks": "Tasks & Setup",
3435

35-
"-- rest-session": {
36+
"-- rest-sessions": {
3637
"type": "separator",
37-
"title": "Rest"
38+
"title": "Rest Sessions"
3839
},
3940

4041
"-- resources": {
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
---
2+
title: Connect Browser
3+
description: Learn how to connect to a sandbox in the browser with the CodeSandbox SDK.
4+
---
5+
6+
import { Callout } from 'nextra-theme-docs'
7+
8+
# Connect Browser
9+
10+
Connecting to a Sandbox in the browser requires some collaboration with your server. Create an endpoint that will resume the sandbox and create a browser session:
11+
12+
```ts
13+
export const GET = async ({ params }) => {
14+
const sandbox = await sdk.sandbox.resume(params.sandboxId);
15+
const session = await sandbox.createBrowserSession();
16+
17+
return session
18+
}
19+
```
20+
21+
And in the browser:
22+
23+
```ts
24+
import { connectToSandbox } from '@codesandbox/sdk/browser';
25+
26+
const session = await connectToSandbox({
27+
id: '123',
28+
getSession: (id) => fetch(`/api/sandboxes/${id}`).then(res => res.json())
29+
});
30+
31+
await session.fs.writeTextFile('test.txt', 'Hello World');
32+
```
33+
34+
The Browser sessions automatically manages the connection and will reconnect if the connection is lost. This is controlled by an option called `onFocusChange`.
35+
36+
```ts
37+
const session = await connectToSandbox({
38+
id: '123',
39+
getSession: (id) => fetch(`/api/sandboxes/${id}`).then(res => res.json()),
40+
onFocusChange: (notify) => {
41+
const onVisibilityChange = () => {
42+
notify(document.visibilityState === 'visible');
43+
}
44+
45+
document.addEventListener('visibilitychange', onVisibilityChange);
46+
47+
return () => {
48+
document.removeEventListener('visibilitychange', onVisibilityChange);
49+
}
50+
}
51+
});
52+
```
53+
54+
By telling the browser session when it is in focus it will automatically reconnect when hibernated, unless you explicitly disconnected the session.
55+
56+
While the `connectToSandbox` promise is resolving you can also listen to initialization events to show a loading state:
57+
58+
```ts
59+
const session = await connectToSandbox({
60+
id: '123',
61+
getSession: (id) => fetch(`/api/sandboxes/${id}`).then(res => res.json()),
62+
onInitCb: (event) => {}
63+
});
64+
```
65+
66+
## Disconnecting the Session
67+
68+
Disconnecting the session will end the session and automatically hibernate the sandbox after a timeout.
69+
70+
```ts
71+
const sandbox = await sdk.sandbox.resume('sandbox-id')
72+
const session = await sandbox.connect()
73+
74+
await session.disconnect();
75+
```

packages/projects-docs/pages/sdk/connect.mdx

Lines changed: 0 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -16,61 +16,6 @@ const session = await sandbox.connect()
1616
await session.fs.writeTextFile('test.txt', 'Hello World');
1717
```
1818

19-
## Connect in Browser
20-
21-
Connecting to a Sandbox in the browser requires some collaboration with your server. Create an endpoint that will resume the sandbox and create a browser session:
22-
23-
```ts
24-
export const GET = async ({ params }) => {
25-
const sandbox = await sdk.sandbox.resume(params.sandboxId);
26-
const session = await sandbox.createBrowserSession();
27-
28-
return session
29-
}
30-
```
31-
32-
And in the browser:
33-
34-
```ts
35-
import { connectToSandbox } from '@codesandbox/sdk/browser';
36-
37-
const session = await connectToSandbox({
38-
getSession: () => fetch(`/api/sandboxes/123`).then(res => res.json())
39-
});
40-
41-
await session.fs.writeTextFile('test.txt', 'Hello World');
42-
```
43-
44-
The Browser sessions automatically manages the connection and will reconnect if the connection is lost. This is controlled by an option called `onFocusChange`.
45-
46-
```ts
47-
const session = await connectToSandbox({
48-
getSession: () => fetch(`/api/sandboxes/123`).then(res => res.json()),
49-
onFocusChange: (notify) => {
50-
const onVisibilityChange = () => {
51-
notify(document.visibilityState === 'visible');
52-
}
53-
54-
document.addEventListener('visibilitychange', onVisibilityChange);
55-
56-
return () => {
57-
document.removeEventListener('visibilitychange', onVisibilityChange);
58-
}
59-
}
60-
});
61-
```
62-
63-
By telling the browser session when it is in focus it will automatically reconnect when hibernated, unless you explicitly disconnected the session.
64-
65-
While the `connectToSandbox` promise is resolving you can also listen to initialization events to show a loading state:
66-
67-
```ts
68-
const session = await connectToSandbox({
69-
getSession: () => fetch(`/api/sandboxes/123`).then(res => res.json()),
70-
onInitCb: (event) => {}
71-
});
72-
```
73-
7419
## Disconnecting the Session
7520

7621
Disconnecting the session will end the session and automatically hibernate the sandbox after a timeout.

packages/projects-docs/pages/sdk/create-resume.mdx

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,8 @@ const sandbox = await sdk.sandbox.create({
6969
title: 'my-sandbox',
7070
description: 'My sandbox',
7171
tags: ['my-tag'],
72-
72+
privacy: 'public'
73+
path: '/users/some-user-folder'
7374
})
7475
```
7576

packages/projects-docs/pages/sdk/filesystem.mdx

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -20,20 +20,20 @@ You can read & write files using an api that's similer to the Node.js fs module:
2020

2121
```ts
2222
const sandbox = await sdk.sandbox.create()
23-
const client = await sandbox.connect()
23+
const session = await sandbox.connect()
2424

2525
// Writing text files
26-
await client.fs.writeTextFile("./hello.txt", "Hello, world!");
26+
await session.fs.writeTextFile("./hello.txt", "Hello, world!");
2727

2828
// Reading text files
29-
const content = await client.fs.readTextFile("./hello.txt");
29+
const content = await session.fs.readTextFile("./hello.txt");
3030
console.log(content);
3131

3232
// Writing binary files
33-
await client.fs.writeFile("./hello.bin", new Uint8Array([1, 2, 3]));
33+
await session.fs.writeFile("./hello.bin", new Uint8Array([1, 2, 3]));
3434

3535
// Reading binary files
36-
const content = await client.fs.readFile("./hello.bin");
36+
const content = await session.fs.readFile("./hello.bin");
3737
console.log(content);
3838
```
3939

@@ -45,12 +45,12 @@ Uploading and downloading files can be done using the same methods as writing an
4545
import fs from "node:fs";
4646

4747
const sandbox = await sdk.sandbox.create()
48-
const client = await sandbox.connect()
48+
const session = await sandbox.connect()
4949

5050
const myBinaryFile = fs.readFileSync("./my-binary-file");
51-
await client.fs.writeFile("./my-binary-file", myBinaryFile);
51+
await session.fs.writeFile("./my-binary-file", myBinaryFile);
5252

53-
const content = await client.fs.readFile("./my-binary-file");
53+
const content = await session.fs.readFile("./my-binary-file");
5454
fs.writeFileSync("./my-binary-file", content);
5555
```
5656

@@ -66,7 +66,7 @@ console.log(downloadUrl);
6666
You can list files & directories in a directory using the `readdir` method.
6767

6868
```ts
69-
const filesOrDirs = await client.fs.readdir("./");
69+
const filesOrDirs = await session.fs.readdir("./");
7070

7171
console.log(filesOrDirs);
7272
```
@@ -76,9 +76,9 @@ console.log(filesOrDirs);
7676
You can copy, rename & delete files using the `copy`, `rename` & `remove` methods.
7777

7878
```ts
79-
await client.fs.copy("./hello.txt", "./hello-copy.txt");
80-
await client.fs.rename("./hello-copy.txt", "./hello-renamed.txt");
81-
await client.fs.remove("./hello-renamed.txt");
79+
await session.fs.copy("./hello.txt", "./hello-copy.txt");
80+
await session.fs.rename("./hello-copy.txt", "./hello-renamed.txt");
81+
await session.fs.remove("./hello-renamed.txt");
8282
```
8383

8484
### Watching Files

packages/projects-docs/pages/sdk/index.mdx

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -44,24 +44,24 @@ import { CodeSandbox } from "@codesandbox/sdk";
4444

4545
const sdk = new CodeSandbox(process.env.CSB_API_KEY!);
4646
const sandbox = await sdk.sandbox.create()
47-
const client = await sandbox.connect()
47+
const session = await sandbox.connect()
4848

49-
await client.shells.python.run("print(1+1)");
50-
await client.shells.run('echo "Hello World"');
49+
await session.shells.python.run("print(1+1)");
50+
await session.shells.run('echo "Hello World"');
5151

5252
// We can also start shells in the background by not awaiting them
53-
const shellInfo = client.shells.run("npx -y serve .");
53+
const shellInfo = session.shells.run("npx -y serve .");
5454

5555
// Wait for port to open
56-
const portInfo = await client.ports.waitForPort(3000);
56+
const portInfo = await session.ports.waitForPort(3000);
5757
console.log(portInfo.url);
5858

5959
// And, we can clone(!) the sandbox! This takes 1-3s.
6060
const sandbox2 = await sdk.sandbox.fork(sandbox.id)
61-
const client2 = await sandbox2.connect()
61+
const session2 = await sandbox2.connect()
6262

6363
// Sandbox 2 will have the same processes running as sandbox 1
64-
const portInfo2 = await client2.ports.waitForPort(3000);
64+
const portInfo2 = await session2.ports.waitForPort(3000);
6565
console.log(portInfo2.url);
6666

6767
// Finally, we can hibernate the sandbox. This will snapshot the sandbox and stop it.

packages/projects-docs/pages/sdk/ports.mdx

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -27,16 +27,16 @@ You can listen for ports being opened and closed in your sandbox:
2727

2828
```ts
2929
const sandbox = await sdk.sandbox.create()
30-
const client = await sandbox.connect()
30+
const session = await sandbox.connect()
3131

3232
// Listen for ports being opened
33-
const listener1 = client.ports.onDidPortOpen((portInfo) => {
33+
const listener1 = session.ports.onDidPortOpen((portInfo) => {
3434
console.log(`Port ${portInfo.port} opened`);
3535
console.log(`Preview URL: ${portInfo.getPreviewUrl()}`);
3636
});
3737

3838
// Listen for ports being closed
39-
const listener2 = client.ports.onDidPortClose((port) => {
39+
const listener2 = session.ports.onDidPortClose((port) => {
4040
console.log(`Port ${port} closed`);
4141
});
4242

@@ -51,16 +51,16 @@ You can get information about currently opened ports:
5151

5252
```ts
5353
const sandbox = await sdk.sandbox.create()
54-
const client = await sandbox.connect()
54+
const session = await sandbox.connect()
5555

5656
// Get all opened ports
57-
const openPorts = client.ports.getOpenedPorts();
57+
const openPorts = session.ports.getOpenedPorts();
5858
for (const port of openPorts) {
5959
console.log(`Port ${port.port} is open at ${port.hostname}`);
6060
}
6161

6262
// Get preview URL for a specific port
63-
const previewUrl = client.ports.getPreviewUrl(3000);
63+
const previewUrl = session.ports.getPreviewUrl(3000);
6464
if (previewUrl) {
6565
console.log(`Preview available at: ${previewUrl}`);
6666
}
@@ -72,13 +72,13 @@ When starting services, you often need to wait for a port to become available:
7272

7373
```ts
7474
const sandbox = await sdk.sandbox.create()
75-
const client = await sandbox.connect()
75+
const session = await sandbox.connect()
7676

7777
// Start a development server
78-
client.shells.run("npm run dev");
78+
session.shells.run("npm run dev");
7979

8080
// Wait for the dev server port to open
81-
const portInfo = await client.ports.waitForPort(3000);
81+
const portInfo = await session.ports.waitForPort(3000);
8282
console.log(`Dev server is ready at: ${portInfo.getPreviewUrl()}`);
8383
```
8484

@@ -90,13 +90,13 @@ Here's a complete example of starting a web server and getting its preview URL:
9090

9191
```ts
9292
const sandbox = await sdk.sandbox.create()
93-
const client = await sandbox.connect()
93+
const session = await sandbox.connect()
9494

9595
// Start the server
96-
client.shells.run("npx serve -y .");
96+
session.shells.run("npx serve -y .");
9797

9898
// Wait for the server to be ready
99-
const portInfo = await client.ports.waitForPort(3000);
99+
const portInfo = await session.ports.waitForPort(3000);
100100

101101
// Get the preview URL with custom protocol
102102
const httpUrl = portInfo.getPreviewUrl("http://");
@@ -113,10 +113,10 @@ When working with multiple services, you might want to monitor several ports:
113113

114114
```ts
115115
const sandbox = await sdk.sandbox.create()
116-
const client = await sandbox.connect()
116+
const session = await sandbox.connect()
117117

118118
// Start monitoring before launching services
119-
client.ports.onDidPortOpen((portInfo) => {
119+
session.ports.onDidPortOpen((portInfo) => {
120120
switch (portInfo.port) {
121121
case 3000:
122122
console.log("Frontend server ready");
@@ -131,5 +131,5 @@ client.ports.onDidPortOpen((portInfo) => {
131131
});
132132

133133
// Start your services
134-
client.shells.run("npm run start:all");
134+
session.shells.run("npm run start:all");
135135
```

0 commit comments

Comments
 (0)