Movatterモバイル変換


[0]ホーム

URL:


Skip to content
Cloudflare Docs
Log in

The Context API provides methods to manage the lifecycle of your Worker or Durable Object.

Context is exposed via the following places:

Note that the Context API is available strictly in stateless contexts, that is, notDurable Objects. However, Durable Objects have a different object, theDurable Object State, which is available asthis.ctx inside a Durable Object class, and provides some of the same functionality as the Context API.

props

ctx.props provides a way to pass additional configuration to a worker based on the context in which it was invoked. For example, when your Worker is called by another Worker,ctx.props can provide information about the calling worker.

For example, imagine that you are configuring a Worker called "frontend-worker", which must talk to another Worker called "doc-worker" in order to manipulate documents. You might configure "frontend-worker" with aService Binding like:

{
"services":[
{
"binding":"DOC_SERVICE",
"service":"doc-worker",
"entrypoint":"DocServiceApi",
"props":{
"clientId":"frontend-worker",
"permissions":[
"read",
"write"
]
}
}
]
}

Now frontend-worker can make calls to doc-worker with code likeenv.DOC_SERVICE.getDoc(id). This will make aRemote Procedure Call invoking the methodgetDoc() of the classDocServiceApi, aWorkerEntrypoint class exported by doc-worker.

The configuration contains aprops value. This in an arbitrary JSON value. When theDOC_SERVICE binding is used, theDocServiceApi instance receiving the call will be able to access thisprops value asthis.ctx.props. Here, we've configuredprops to specify that the call comes from frontend-worker, and that it should be allowed to read and write documents. However, the contents ofprops can be anything you want.

The Workers platform is designed to ensure thatctx.props can only be set by someone who has permission to edit and deploy the worker to which it is being delivered. This means that you can trust that the content ofctx.props is authentic. There is no need to use secret keys or cryptographic signatures in actx.props value.

ctx.props can also be used to configure an RPC interface to represent aspecific resource, thus creating a "custom binding". For example, we could configure a Service Binding to our "doc-worker" which grants access only to a specific document:

{
"services":[
{
"binding":"FOO_DOCUMENT",
"service":"doc-worker",
"entrypoint":"DocumentApi",
"props":{
"docId":"e366592caec1d88dff724f74136b58b5",
"permissions":[
"read",
"write"
]
}
}
]
}

Here, we've placed adocId property inctx.props. TheDocumentApi class could be designed to provide an API to the specific document identified byctx.props.docId, and enforcing the given permissions.

exports

ctx.exports provides automatically-configured "loopback" bindings for all of your top-level exports.

  • For each top-level export thatextends WorkerEntrypoint (or simply implements a fetch handler),ctx.exports automatically contains aService Binding.
  • For each top-level export thatextends DurableObject (and which has been configured with storage via amigration),ctx.exports automatically contains aDurable Object namespace binding.

For example:

JavaScript
import{WorkerEntrypoint} from"cloudflare:workers";
exportclassGreeterextendsWorkerEntrypoint{
greet(name){
return`Hello,${name}!`;
}
}
exportdefault{
asyncfetch(request,env,ctx){
letgreeting=awaitctx.exports.Greeter.greet("World");
returnnewResponse(greeting);
},
};

In this example, the default fetch handler calls theGreeter class over RPC, like how you'd use a Service Binding. However, there is no external configuration required.ctx.exports is populatedautomatically from your top-level imports.

Specifyingctx.props when usingctx.exports

Loopback Service Bindings inctx.exports have an extra capability that regular Service Bindings do not: the caller can specify the value ofctx.props that should be delivered to the callee.

JavaScript
import{WorkerEntrypoint} from"cloudflare:workers";
exportclassGreeterextendsWorkerEntrypoint{
greet(name){
return`${this.ctx.props.greeting},${name}!`;
}
}
exportdefault{
asyncfetch(request,env,ctx){
// Make a custom greeter that uses the greeting "Welcome".
letgreeter=ctx.exports.Greeter({ props:{ greeting:"Welcome"}});
// Greet the world. Returns "Welcome, World!"
letgreeting=awaitgreeter.greet("World");
returnnewResponse(greeting);
},
};

Specifying props dynamically is permitted in this case because the caller is the same Worker, and thus can be presumed to be trusted to specify any props. The ability to customize props is particularly useful when the resulting binding is to be passed to another Worker over RPC or used in theenv of adynamically-loaded worker.

Note thatprops values specified in this way are allowed to contain any "persistently" serializable type. This includes all basicstructured clonable data types. It also includes Service Bindings themselves: you can place a Service Binding into theprops of another Service Binding.

TypeScript types forctx.exports andctx.props

If using TypeScript, you should usethewrangler types command to auto-generate types for your project. The generated types will ensurectx.exports is typed correctly.

When declaring an entrypoint class that acceptsprops, make sure to declare it asextends WorkerEntrypoint<Env, Props>, whereProps is the type ofctx.props. See the example above.

waitUntil

ctx.waitUntil() extends the lifetime of your Worker, allowing you to perform work without blocking returning a response, and that may continue after a response is returned. It accepts aPromise, which the Workers runtime will continue executing, even after a response has been returned by the Worker'shandler.

waitUntil is commonly used to:

  • Fire off events to external analytics providers. (note that when you useWorkers Analytics Engine, you do not need to usewaitUntil)
  • Put items into cache using theCache API

The Worker's lifetime is extended for up to 30 seconds after the response is sent or the client disconnects. This time limit is shared across allwaitUntil() calls within the same request — if any Promises have not settled after 30 seconds, they are cancelled. WhenwaitUntil tasks are cancelled, the following warning will be logged toWorkers Logs and any attachedTail Workers:waitUntil() tasks did not complete within the allowed time after invocation end and have been cancelled.

If you need to guarantee that work completes successfully, you should send messages to aQueue and process them in a separate consumer Worker. Queues provide reliable delivery and automatic retries, ensuring your work is not lost.

If you are usingwaitUntil() to emit logs or exceptions, we recommend usingTail Workers instead. Even if your Worker throws an uncaught exception, the Tail Worker will execute, ensuring that you can emit logs or exceptions regardless of the Worker's invocation status.

Cloudflare Queues is purpose-built for performing work out-of-band, without blocking returning a response back to the client Worker.

You can callwaitUntil() multiple times. Similar toPromise.allSettled, even if a promise passed to onewaitUntil call is rejected, promises passed to otherwaitUntil() calls will still continue to execute.

For example:

JavaScript
exportdefault{
asyncfetch(request,env,ctx){
// Forward / proxy original request
letres=awaitfetch(request);
// Add custom header(s)
res=newResponse(res.body,res);
res.headers.set("x-foo","bar");
// Cache the response
// NOTE: Does NOT block / wait
ctx.waitUntil(caches.default.put(request,res.clone()));
// Done
returnres;
},
};

passThroughOnException

The Workers Runtime uses streaming for request and response bodies. It does not buffer the body. Hence, if an exception occurs after the body has been consumed,passThroughOnException() cannot send the body again.

If this causes issues, we recommend cloning the request body and handling exceptions in code. This will protect against uncaught code exceptions. However some exception times such as exceed CPU or memory limits will not be mitigated.

ThepassThroughOnException method allows a Worker tofail open, and pass a request through to an origin server when a Worker throws an unhandled exception. This can be useful when using Workers as a layer in front of an existing service, allowing the service behind the Worker to handle any unexpected error cases that arise in your Worker.

JavaScript
exportdefault{
asyncfetch(request,env,ctx){
// Proxy to origin on unhandled/uncaught exceptions
ctx.passThroughOnException();
thrownewError("Oops");
},
};

[8]
ページ先頭

©2009-2026 Movatter.jp