new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Cloudflare Workers · Runtime APIs · all subjects

handlers

183 notes in this subject, read out of this brain and free to use. This is page 1 of 4.

XMLHttpRequest not supported in Workers runtime

The Workers runtime does not support XMLHttpRequest (XHR). The fetch() API must be used instead.

Fetch handler ctx.passThroughOnException method

The ctx parameter provides a passThroughOnException() method that returns void. This method is used to pass through to the next handler on exception.

Fetch handler env parameter

The env parameter is an object containing the bindings available to the Worker. As long as the environment has not changed, the same object (equal by identity) may be passed to multiple requests. Bindings can also be imported from 'cloudflare:workers' as a global to access them from anywhere in the code.

Fetch handler request parameter

The request parameter in the fetch handler is the incoming HTTP request passed as a Request object.

Fetch handler ctx.waitUntil method

The ctx parameter provides a waitUntil(promise) method that returns void. This method is used to extend the lifetime of the request context.

Fetch handler function signature

The fetch handler is the default export with signature: export default { async fetch(request, env, ctx) { ... } }. It receives an incoming HTTP request as a Request object and must return a Response object to respond to the request.

Fetch handler minimal example

export default { async fetch(request, env, ctx) { return new Response('Hello World!'); }, };

Python Workers handlers in Default class

When writing Workers in Python, handlers are placed in a class named Default that extends the WorkerEntrypoint class, which can be imported from the workers SDK module.

fetch handler receives HTTP request

The fetch() handler receives an HTTP request and can return a response. It is a method on Workers that can receive and process external inputs, and can be invoked from outside your Worker.

fetch handler signature with request env ctx

The fetch handler accepts three parameters: request, env, and ctx. The basic signature is async fetch(request, env, ctx) which returns a Response object.

Handlers definition

Handlers are methods on Workers that can receive and process external inputs, and can be invoked from outside your Worker.

Queue handler documentation location

Queue handler API documentation is available in the Queues configuration section at /queues/configuration/javascript-apis/#consumer.

Queue handler for consuming messages

The queue handler in Cloudflare Workers allows consuming messages from Cloudflare Queues. Messages are handled by implementing a queue handler function in Workers.

ctx.waitUntil() method

ctx.waitUntil(promise) is a void method that registers asynchronous tasks (such as logging, analytics, streaming, and caching) that should settle before the invocation completes. The first ctx.waitUntil to fail will be observed and recorded as the status in the Cron Trigger Past Events table; otherwise it will be reported as a success.

Multiple Cron Triggers with single scheduled() handler

When multiple Cron Triggers are configured for a single Worker, each trigger invokes the same scheduled() handler. Use controller.cron to distinguish which schedule fired and run different logic for each trigger.

Runtime wait behavior for scheduled() handler

The runtime waits for the promise returned by the scheduled() handler to resolve up to the 15-minute duration limit. Using waitUntil() is not necessary for the runtime to wait for a single asynchronous task. waitUntil() is most useful when you need to run multiple concurrent tasks or when you want the outcome of a specific promise to be recorded as the Cron Trigger invocation status.

controller.type property

controller.type is a string that always returns 'scheduled' when the scheduled() handler is invoked.

ctx parameter in scheduled handler

The ctx parameter is an ExecutionContext object containing the context associated with the Worker. Currently, this object contains the waitUntil() function.

controller.scheduledTime property

controller.scheduledTime is a number representing the time the ScheduledEvent was scheduled to be executed in milliseconds since January 1, 1970, UTC. It can be parsed as new Date(controller.scheduledTime).

scheduled() handler syntax

The scheduled() handler is an async function that receives three parameters: controller (a ScheduledController instance), env (an object containing Worker bindings), and ctx (an ExecutionContext object). In JavaScript: export default { async scheduled(controller, env, ctx) { await doSomeTaskOnASchedule(); } }

Multiple Cron Triggers configuration example

Example configuration in wrangler.jsonc: { "triggers": { "crons": ["*/5 * * * *", "0 0 * * *"] } }

Handling multiple cron triggers with switch statement

Example code to handle multiple cron triggers by checking controller.cron value: export default { async scheduled(controller, env, ctx) { switch (controller.cron) { case "*/5 * * * *": await fetch("https://example.com/api/sync"); break; case "0 0 * * *": await env.MY_KV.put("last-cleanup", new Date().toISOString()); break; } } }

Testing scheduled() handler locally

The scheduled() handler can be tested in local development by sending an HTTP request to /cdn-cgi/handler/scheduled. Pass ?format=json to return the structured scheduled handler result. Example: curl "http://localhost:8787/cdn-cgi/handler/scheduled?format=json"

controller.cron property

controller.cron is a string containing the value of the Cron Trigger that started the ScheduledEvent. The value is the exact cron expression string from the configuration and must match character-for-character, including spacing.

TailRequest method property

The method property of a TailRequest object is a string containing the HTTP request method.

TailRequest cf property

The cf property of a TailRequest object contains the data from IncomingRequestCfProperties.

FetchEventInfo response property

The response property of a FetchEventInfo object is a TailResponse object containing details about the HTTP response.

FetchEventInfo request property

The request property of a FetchEventInfo object is a TailRequest object containing details about the HTTP request.

TailItem outcome property possible values

The outcome property of a TailItem is a string with possible values: 'unknown' (outcome status was not set), 'ok' (invocation succeeded), 'exception' (unhandled exception thrown from JavaScript error, fetch handler without Response, or internal error), 'exceededCpu' (exceeded CPU limits), 'exceededMemory' (exceeded memory limits), 'scriptNotFound' (internal error retrieving script), 'canceled' (invocation canceled before completion, commonly because client disconnected), 'responseStreamDisconnected' (response stream disconnected during deferred proxying).

TailItem exceptions property

The exceptions property of a TailItem is an array of TailException objects. A single Worker invocation might result in multiple unhandled exceptions, since a Worker can register multiple asynchronous tasks.

TailItem logs property

The logs property of a TailItem is an array of TailLog objects that record information sent to console functions.

tail() handler invocation timing

The tail() handler is called once each time the connected producer Worker is invoked.

tail event waitUntil method

The event.waitUntil(promise) method is a void function that allows tail handlers to perform asynchronous work. Unlike fetch event handlers, tail handlers do not return a value, so waitUntil is the only way for Tail Workers to do asynchronous work.

tail() handler Python syntax

The tail() handler in Python is implemented as an async method within a WorkerEntrypoint class. Example: class Default(WorkerEntrypoint): async def tail(self, events, env, ctx): await fetch('<YOUR_ENDPOINT>', method='POST', body=json.dumps(events))

TailException timestamp property

The timestamp property of a TailException object is a number measured in epoch time indicating when the exception occurred.

TailException name property

The name property of a TailException object is a string containing the error type (for example, 'Error', 'TypeError', etc.).

tail event type property

The event.type property is a string that always returns 'tail' for tail handler events.

tail() handler env parameter

The env parameter is an object containing the bindings associated with your Worker using ES modules format, such as KV namespaces and Durable Objects.

tail() handler basic syntax

The tail() handler is implemented as an async function that receives three parameters: events, env, and ctx. Example in JavaScript: export default { async tail(events, env, ctx) { fetch('<YOUR_ENDPOINT>', { method: 'POST', body: JSON.stringify(events) }) } }

tail() handler events parameter

The events parameter is an array of TailItems. One TailItem is collected for each event that triggers a Worker. For Workers for Platforms customers with a Tail Worker installed on the dynamic dispatch Worker, events will contain two elements: one for the dynamic dispatch Worker and one for the User Worker.

TailException message property

The message property of a TailException object is an object containing the error description (for example, '"x" is not a function').

TailLog message property

The message property of a TailLog object is an object containing the array of parameters passed to the console function.

TailRequest headers property

The headers property of a TailRequest object contains header name/value entries that are redacted by default. Header names are lowercased, and values associated with duplicate header names are concatenated with the string ', ' (comma space), similar to the Fetch standard.

tail() handler ctx parameter

The ctx parameter is an object containing the context associated with your Worker using ES modules format. Currently, this object contains the waitUntil function.

TailRequest url property

The url property of a TailRequest object is a string containing the HTTP request URL, redacted by default.

tail event traces property

The event.traces property is an array of TailItems. One TailItem is collected for each event that triggers a Worker.

TailRequest getUnredacted() method

The getUnredacted() method of a TailRequest object returns a TailRequest object with unredacted properties. This bypasses the default redaction of sensitive information.

TailItem scriptName property

The scriptName property of a TailItem is a string containing the name of the producer script.

TailItem event property

The event property of a TailItem contains information about the Worker's triggering event. For fetch events, it contains a FetchEventInfo object. For other event types, it is null.

TailItem eventTimestamp property

The eventTimestamp property of a TailItem is a number measured in epoch time indicating when the event occurred.

TailResponse status property

The status property of a TailResponse object is a number containing the HTTP status code.

TailRequest header redaction rules

Header redaction in TailRequest uses heuristic rules that may have false positives and negatives. Header values will be the string 'REDACTED' when the case-insensitive header name is 'cookie', 'set-cookie', or contains a substring 'auth', 'key', 'secret', 'token', or 'jwt'.

TailLog level property

The level property of a TailLog object is a string indicating the console function that was called. Possible values are: 'debug', 'info', 'log', 'warn', 'error'.

outcome property differs from HTTP status

Outcome is equivalent to the exit status of a script and an indicator of whether it has fully run to completion. Outcome may differ from HTTP response code. For example, a script may successfully process a request but return a 4xx/5xx response, or send a 200 response but have an asynchronous task via waitUntil() that later exceeds CPU or memory limits.

TailLog timestamp property

The timestamp property of a TailLog object is a number measured in epoch time indicating when the log entry was created.

TailRequest URL redaction rules

URL redaction in TailRequest replaces greedily matched substrings of ID characters (a-z, A-Z, 0-9, '+', '-', '_') with 'REDACTED' if they meet hex or base-64 ID criteria. Hex ID: contains 32 or more hex digits and contains only hex digits and separators. Base-64 ID: contains 21 or more characters with at least two uppercase, two lowercase, and two digits.

Headers.get returns USVString not ByteString

In Cloudflare Workers, the Headers.get method returns a USVString instead of a ByteString as specified by the web standard. For most scenarios, this should have no noticeable effect.

Set-Cookie append example

Example showing multiple Set-Cookie headers: ```js const headers = new Headers(); headers.append("Set-Cookie", "cookie1=value_for_cookie_1; Path=/; HttpOnly;"); headers.append("Set-Cookie", "cookie2=value_for_cookie_2; Path=/; HttpOnly;"); console.log(headers.getAll("Set-Cookie")); // Array(2) [ cookie1=value_for_cookie_1; Path=/; HttpOnly;, cookie2=value_for_cookie_2; Path=/; HttpOnly; ] ``` This shows that append() on Set-Cookie creates separate header entries rather than comma-delimited concatenation.

Set-Cookie append behavior in Workers

Due to RFC 6265 prohibiting folding multiple Set-Cookie headers into a single header, the Headers.append method in Workers allows setting multiple Set-Cookie response headers instead of appending the value onto an existing header.

getAll() method only works with Set-Cookie

Despite being obsolete in web browsers, Workers still provides the Headers.getAll method specifically for use with the Set-Cookie header because cookies often contain date strings with commas, making parsing difficult. Attempting to use Headers.getAll with other header names will throw an error.

Give your agent this brain