サンドボックスは 送信ハンドラー を通じて、Workers バインディング(KV、R2、D1、Durable Objects など)にアクセスできます。送信ハンドラーはサンドボックスからの HTTP リクエストを傍受し、Workers ランタイム内で実行します。設定済みのバインディングは、すべてそこで使えます。
サンドボックスは仮想ホスト名(例: http://my.kv/some-key)へ通常の HTTP リクエストを送り、送信ハンドラーがバインドしたリソースで解決します。サンドボックス内に SDK やクライアントライブラリは不要です。
仮想ホスト名ごとに outboundByHost ハンドラーを定義します。env 引数で、Wrangler 設定に宣言したすべてのバインディングにアクセスできます。
export class MySandbox extends Sandbox {}
MySandbox.outboundByHost = {
"my.kv": async (request, env, ctx) => {
const url = new URL(request.url);
const key = url.pathname.slice(1);
const value = await env.KV.get(key);
return new Response(value ?? "", { status: value ? 200 : 404 });
},
"my.r2": async (request, env, ctx) => {
const url = new URL(request.url);
// Scope access to this sandbox's ID
const path = `${ctx.containerId}${url.pathname}`;
const object = await env.R2.get(path);
return new Response(object?.body ?? null, { status: object ? 200 : 404 });
},
};export class MySandbox extends Sandbox {}
MySandbox.outboundByHost = {
"my.kv": async (request: Request, env: Env, ctx: OutboundHandlerContext) => {
const url = new URL(request.url);
const key = url.pathname.slice(1);
const value = await env.KV.get(key);
return new Response(value ?? "", { status: value ? 200 : 404 });
},
"my.r2": async (request: Request, env: Env, ctx: OutboundHandlerContext) => {
const url = new URL(request.url);
// Scope access to this sandbox's ID
const path = `${ctx.containerId}${url.pathname}`;
const object = await env.R2.get(path);
return new Response(object?.body ?? null, { status: object ? 200 : 404 });
},
};サンドボックスが http://my.kv/some-key を呼ぶと、ハンドラーが KV バインディングで解決します。http://my.r2/file.png への呼び出しは、現在のサンドボックスインスタンスにスコープして R2 から読み取ります。
ctx 引数は containerId を公開します。送信ハンドラーから、サンドボックス自身の Durable Object とやり取りできます。
export class MySandbox extends Sandbox {}
MySandbox.outboundByHost = {
"get-state.do": async (request, env, ctx) => {
const id = env.MY_SANDBOX.idFromString(ctx.containerId);
const stub = env.MY_SANDBOX.get(id);
// Assumes getStateForKey is defined on your DO
return stub.getStateForKey(request.body);
},
};export class MySandbox extends Sandbox {}
MySandbox.outboundByHost = {
"get-state.do": async (
request: Request,
env: Env,
ctx: { containerId: string },
) => {
const id = env.MY_SANDBOX.idFromString(ctx.containerId);
const stub = env.MY_SANDBOX.get(id);
// Assumes getStateForKey is defined on your DO
return stub.getStateForKey(request.body);
},
};- 送信トラフィックを処理する — サンドボックスからのすべての送信 HTTP をブロック、許可、傍受する
- サンドボックスオプション — サンドボックスの動作を設定する
- 環境変数 — シークレットと環境変数を設定する