fetch
Send HTTP requests from the cloud, read responses, and create HTTP services with a default export.
Global fetch makes requests from the cloud runtime. Use it to call public APIs, upload data, and stream responses without importing a module.
Use export default { fetch } to create an HTTP service, with your own fetch function handling incoming requests.
const response = await fetch('https://example.com');
if (!response.ok) throw new Error(`HTTP ${response.status}`);
console.log(await response.text());fetch(input, init?)
Function: sends a request and returns a response once its headers arrive. Reading the body is a separate asynchronous operation.
declare function fetch(input: string | URL | Request, init?: RequestInit): Promise<Response>;| Parameter | Type | Required | Description |
|---|---|---|---|
input | string / URL / Request | Yes | An absolute URL or an existing request |
init | RequestInit | No | Request configuration; supplied fields override corresponding settings in the input request |
init.method | string | No | Defaults to GET; GET / HEAD cannot carry a body |
init.headers | HeadersInit | No | A Headers object, string-valued record, or array of [name, value] pairs |
init.body | BodyInit / null | No | A string, Blob / File, ArrayBuffer / ArrayBufferView (including TypedArray and DataView), FormData, URLSearchParams, or byte ReadableStream |
init.signal | AbortSignal / null | No | Cancels waiting for a response or reading its body; no active cancellation by default |
init.redirect | RequestRedirect | No | follow (default), manual, or error |
Return value: Promise<Response>. HTTP 4xx / 5xx responses resolve normally; inspect ok or status. Network, DNS, TLS, or destination validation failures reject the promise. Invalid methods and already-used bodies can also cause TypeError.
For FormData, let the runtime generate a Content-Type containing its boundary. For JSON, use JSON.stringify() and set the appropriate header. Upload ReadableStreams must yield byte chunks.
These RequestInit fields are also accepted, but currently only retained on the request object. They do not implement the corresponding browser cache, cookie, CORS, or integrity facilities:
| Field | Type / values | Default and description |
|---|---|---|
referrer | string | about:client; also accepts an empty string or absolute URL |
referrerPolicy | ReferrerPolicy | Defaults to an empty string; also accepts no-referrer, no-referrer-when-downgrade, same-origin, origin, strict-origin, origin-when-cross-origin, strict-origin-when-cross-origin, and unsafe-url |
mode | 'cors' / 'same-origin' / 'no-cors' | cors; navigate is rejected |
credentials | 'omit' / 'same-origin' / 'include' | same-origin; does not automatically attach login cookies |
cache | 'default' / 'no-store' / 'reload' / 'no-cache' / 'force-cache' / 'only-if-cached' | default; only-if-cached requires same-origin mode |
integrity | string | Empty string; no subresource integrity verification |
keepalive | boolean | false; does not guarantee requests survive task completion |
priority | 'auto' / 'high' / 'low' | auto; no network scheduling priority guarantee |
Network scope and request options
HTTP(S) requests allow public destinations only. DNS results and every redirect target are checked. Loopback, private, and other non-public addresses are rejected. data: and blob: URLs can read inline data or objects in the current environment without HTTP networking.
Server-side requests have no page-relative URL base, browser login Cookie Jar, or browser HTTP cache. Browser-side options such as credentials, mode, and cache do not establish those facilities. Set authentication headers explicitly. Host proxies and certificate trust are managed by the platform; application environment variables cannot reconfigure the request client.
Response
The response returned by fetch() exposes these properties:
| Property | Type | Description |
|---|---|---|
ok | boolean | Whether the status is 200–299 |
status | number | HTTP status code |
statusText | string | Status text, which can be empty |
headers | Headers | Response headers; headers.get(name) returns a string or null; also iterable |
url | string | Response URL |
redirected | boolean | Whether automatic redirection occurred |
type | ResponseType | Response type |
body | ReadableStream<Uint8Array> / null | A byte stream read on demand; null for bodyless responses such as HEAD |
bodyUsed | boolean | Whether body consumption has started |
Body methods
These methods take no arguments. Except for clone(), each consumes the whole body and returns a promise. A body can be consumed only once.
| Method | Function | Return value |
|---|---|---|
response.text() | Decode the body as UTF-8 | Promise<string> |
response.json() | Parse the body as JSON; invalid JSON rejects | Promise<any> |
response.arrayBuffer() | Read all original bytes | Promise<ArrayBuffer> |
response.bytes() | Read all bytes as a typed array | Promise<Uint8Array> |
response.blob() | Read a binary object with its media type | Promise<Blob> |
response.formData() | Parse a supported form-encoded body | Promise<FormData> |
response.clone() | Copy an unused, unlocked response and tee its body | Response, returned synchronously |
For streaming reads, use response.body.getReader() and release the reader lock afterward. If you do not need the body, call await response.body?.cancel(); cancel through the reader if it holds the lock. Full-body reads require corresponding memory. Consume or cancel both branches of a clone as well.
Cancellation and timeouts
fetch() has no timeoutMs option. Pass AbortSignal.timeout(milliseconds) or call AbortController.abort(reason?). Cancellation affects the request and its response body, rejecting the promise or a pending read.
const response = await fetch('https://example.com', {
signal: AbortSignal.timeout(10000),
});
console.log(await response.text());A timeout signal normally rejects with TimeoutError; a controller without a custom reason uses AbortError. Handle a supplied reason as that value. Task stop or expiry also cleans up network resources. Cancellation cannot undo an operation already performed by the destination service.
Create an HTTP service
Default-export an object containing a fetch function from the entry module, and the runtime runs the instance as a public HTTP service. This fetch is your request handler, receiving incoming requests and returning responses:
function fetch(request) {
const url = new URL(request.url);
return Response.json({
message: 'Hello from runtime',
method: request.method,
path: url.pathname,
});
}
export default { fetch };You can also write export default { fetch(request) { /* return a Response */ } }. A named export function fetch() {} alone does not register a service. The example declares a module-level function named fetch; use globalThis.fetch(url, options) for outgoing requests to avoid calling your own handler again.
Handler and parameters
The handler signature is fetch(request, env, ctx). Unused parameters can be omitted. For ordinary functions and object methods, this is the default-exported object.
| Parameter | Type | Description |
|---|---|---|
request | Request | The incoming method, URL, headers, and body |
env | Readonly<Record<string, never>> | Frozen empty object; import lexmount:env for instance environment variables |
ctx | JsdExecutionContext | Registers asynchronous work with waitUntil() that can continue after the response |
Use request.method, new URL(request.url), and request.headers.get(name) for the method, path, query parameters, and headers. Read the body with methods such as request.text() and request.json(). A body can be consumed only once.
Return value: Response or Promise<Response>. Use new Response(body, { status, headers }) for text, HTML, binary data, or byte streams, or Response.json(data, init?) for JSON. See Response above for properties and body methods. If the handler throws, its promise rejects, or it returns a non-Response value, that request receives HTTP 500 and the error is logged. The service continues handling later requests.
Background work
ctx.waitUntil(promise: PromiseLike<unknown>): void registers asynchronous work without blocking the response. Rejections are logged and do not change a response that has already been returned. Read any request body needed by background work before returning the response, rather than reading a closed request later.
Stop, rerun, timeout, or runtime shutdown can interrupt requests and background work. waitUntil() does not guarantee completion. See the public HTTP example for a complete script with path routing and background work.
Run and lifecycle
- Create or select an instance in Instances, open Code, and save the example as the entry JS/MJS file.
- Set the maximum runtime and select Run.
0means no time limit; other values stop the service when the limit is reached. - Wait for the service to become ready, then select Visit in the instance list to open the public URL provided by the console.
The runtime starts the service automatically after the entry module finishes evaluating. You do not need to configure a listening port or write a keep-alive loop. Top-level initialization can use await, but must finish before requests can be served. The public URL allows anonymous access; validate requests in your handler if authentication is required, and use the service address provided by the console.
The service keeps running until you stop it, rerun to replace the current execution, or reach the maximum runtime. Each rerun uses a new JavaScript environment. Write data that must survive across executions to associated persistent storage. Once stopped, the public entry no longer runs that handler.
See jsd.d.ts for type declarations.
