Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
317 changes: 247 additions & 70 deletions src/content/docs/workers/runtime-apis/nodejs/http.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,38 @@ pcx_content_type: configuration
title: http
---

import { Render } from "~/components"
import { Render } from "~/components";

<Render file="nodejs-compat-howto" />

## Compatibility flags

### Client-side methods

To use the HTTP client-side methods (`http.get`, `http.request`, etc.), you must enable the [`enable_nodejs_http_modules`](/workers/configuration/compatibility-flags/) compatibility flag in addition to the [`nodejs_compat`](/workers/runtime-apis/nodejs/) flag.

This flag is automatically enabled for Workers using a [compatibility date](/workers/configuration/compatibility-dates/) of `2025-08-15` or later when `nodejs_compat` is enabled. For Workers using an earlier compatibility date, you can manually enable it by adding the flag to your `wrangler.toml`:

```toml
compatibility_flags = ["nodejs_compat", "enable_nodejs_http_modules"]
```

### Server-side methods

To use the HTTP server-side methods (`http.createServer`, `http.Server`, `http.ServerResponse`), you must enable the `enable_nodejs_http_server_modules` compatibility flag in addition to the [`nodejs_compat`](/workers/runtime-apis/nodejs/) flag.

This flag is automatically enabled for Workers using a [compatibility date](/workers/configuration/compatibility-dates/) of `2025-09-01` or later when `nodejs_compat` is enabled. For Workers using an earlier compatibility date, you can manually enable it by adding the flag to your `wrangler.toml`:

```toml
compatibility_flags = ["nodejs_compat", "enable_nodejs_http_server_modules"]
```

To use both client-side and server-side methods, enable both flags:

```toml
compatibility_flags = ["nodejs_compat", "enable_nodejs_http_modules", "enable_nodejs_http_server_modules"]
```

## get

An implementation of the Node.js [`http.get`](https://nodejs.org/docs/latest/api/http.html#httpgetoptions-callback) method.
Expand All @@ -18,25 +46,25 @@ fetch or similar handler. Outside of such a handler, attempts to use `get` will
an error.

```js
import { get } from 'node:http';
import { get } from "node:http";

export default {
async fetch() {
const { promise, resolve, reject } = Promise.withResolvers();
get('http://example.org', (res) => {
let data = '';
res.setEncoding('utf8');
res.on('data', (chunk) => {
get("http://example.org", (res) => {
let data = "";
res.setEncoding("utf8");
res.on("data", (chunk) => {
data += chunk;
});
res.on('end', () => {
res.on("end", () => {
resolve(new Response(data));
});
res.on('error', reject);
}).on('error', reject);
res.on("error", reject);
}).on("error", reject);
return promise;
}
}
},
};
```

The implementation of `get` in Workers is a wrapper around the global
Expand All @@ -58,31 +86,35 @@ fetch or similar handler. Outside of such a handler, attempts to use `request` w
an error.

```js
import { get } from 'node:http';
import { get } from "node:http";

export default {
async fetch() {
const { promise, resolve, reject } = Promise.withResolvers();
get({
method: 'GET',
protocol: 'http:',
hostname: 'example.org',
path: '/'
}, (res) => {
let data = '';
res.setEncoding('utf8');
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
resolve(new Response(data));
});
res.on('error', reject);
}).on('error', reject)
.end();
get(
{
method: "GET",
protocol: "http:",
hostname: "example.org",
path: "/",
},
(res) => {
let data = "";
res.setEncoding("utf8");
res.on("data", (chunk) => {
data += chunk;
});
res.on("end", () => {
resolve(new Response(data));
});
res.on("error", reject);
},
)
.on("error", reject)
.end();
return promise;
}
}
},
};
```

The following options passed to the `request` (and `get`) method are not supported due to the differences required by Coudflare Workers implementation of `node:http` as a wrapper around the global `fetch` API:
Expand All @@ -97,26 +129,17 @@ The following options passed to the `request` (and `get`) method are not support

The [`OutgoingMessage`](https://nodejs.org/docs/latest/api/http.html#class-httpoutgoingmessage) class represents an HTTP response that is sent to the client. It provides methods for writing response headers and body, as well as for ending the response. `OutgoingMessage` extends from the Node.js [`stream.Writable` stream class](https://developers.cloudflare.com/workers/runtime-apis/nodejs/streams/).

```js
import { OutgoingMessage } from 'node:http';
The `OutgoingMessage` class is a base class for outgoing HTTP messages (both requests and responses). It provides methods for writing headers and body data, as well as for ending the message. `OutgoingMessage` extends from the [`Writable` stream class](https://nodejs.org/docs/latest/api/stream.html#class-streamwritable).

export default {
async fetch() {
// ...
const res = new OutgoingMessage();
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('Hello, World!');
res.end();
// ...
}
}
```
Both `ClientRequest` and `ServerResponse` both extend from and inherit from `OutgoingMessage`.

## IncomingMessage

The `IncomingMessage` class represents an HTTP request that is received from the client. It provides methods for reading request headers and body, as well as for ending the request. `IncomingMessage` extends from the `Readable` stream class.

```js
The `IncomingMessage` class represents an HTTP message (request or response). It provides methods for reading headers and body data. `IncomingMessage` extends from the `Readable` stream class.

````js
import { get, IncomingMessage } from 'node:http';
import { ok, strictEqual } from 'node:assert';

Expand All @@ -129,7 +152,37 @@ export default {
// ...
}
}
```

The Workers implementation includes a `cloudflare` property on `IncomingMessage` objects:

```js
import { createServer } from "node:http";
import { httpServerHandler } from "cloudflare:node";

const server = createServer((req, res) => {
console.log(req.cloudflare.cf.country);
console.log(req.cloudflare.cf.ray);
res.write("Hello, World!");
res.end();
});

server.listen(8080);

export default httpServerHandler({ port: 8080 });
````

The `cloudflare.cf` property contains [Cloudflare-specific request properties](/workers/runtime-apis/request/#incomingrequestcfproperties).

The following differences exist between the Workers implementation and Node.js:

- Trailer headers are not supported
- The `socket` attribute **does not extend from `net.Socket`** and only contains the following properties: `encrypted`, `remoteFamily`, `remoteAddress`, `remotePort`, `localAddress`, `localPort`, and `destroy()` method.
- The following `socket` attributes behave differently than their Node.js counterparts:
- `remoteAddress` will return `127.0.0.1` when ran locally
- `remotePort` will return a random port number between 2^15 and 2^16
- `localAddress` will return the value of request's `host` header if exists. Otherwise, it will return `127.0.0.1`
- `localPort` will return the port number assigned to the server instance
- `req.socket.destroy()` falls through to `req.destroy()`

## Agent

Expand All @@ -138,37 +191,161 @@ A partial implementation of the Node.js [`http.Agent'](https://nodejs.org/docs/l
An `Agent` manages HTTP connection reuse by maintaining request queues per host/port. In the workers environment, however, such low-level management of the network connection, ports, etc, is not relevant because it is handled by the Cloudflare infrastructure instead. Accordingly, the implementation of `Agent` in Workers is a stub implementation that does not support connection pooling or keep-alive.

```js
import { get, Agent } from 'node:http';
import { strictEqual } from 'node:assert';
import { Agent } from "node:http";
import { strictEqual } from "node:assert";

const agent = new Agent();
strictEqual(agent.protocol, "http:");
```

## createServer

An implementation of the Node.js [`http.createServer`](https://nodejs.org/docs/latest/api/http.html#httpcreateserveroptions-requestlistener) method.

The `createServer` method creates an HTTP server instance that can handle incoming requests.

```js
import { createServer } from "node:http";
import { httpServerHandler } from "cloudflare:node";

const server = createServer((req, res) => {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Hello from Node.js HTTP server!");
});

server.listen(8080);
export default httpServerHandler({ port: 8080 });
```

## Node.js integration

### httpServerHandler

The `httpServerHandler` function integrates Node.js HTTP servers with the Cloudflare Workers request model. It supports two API patterns:

```js
import http from "node:http";
import { httpServerHandler } from "cloudflare:node";

const server = http.createServer((req, res) => {
res.end("hello world");
});

// Pass server directly (simplified) - automatically calls listen() if needed
export default httpServerHandler(server);

// Or use port-based routing for multiple servers
server.listen(8080);
export default httpServerHandler({ port: 8080 });
```

The handler automatically routes incoming Worker requests to your Node.js server. When using port-based routing, the port number acts as a routing key to determine which server handles requests, allowing multiple servers to coexist in the same Worker.

### handleAsNodeRequest

For more direct control over request routing, you can use the `handleAsNodeRequest` function from `cloudflare:node`. This function directly routes a Worker request to a Node.js server running on a specific port:

```js
import { createServer } from "node:http";
import { handleAsNodeRequest } from "cloudflare:node";

const server = createServer((req, res) => {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Hello from Node.js HTTP server!");
});

server.listen(8080);

export default {
async fetch() {
fetch(request) {
return handleAsNodeRequest(8080, request);
},
};
```

const agent = new Agent();
get({
hostname: 'example.org',
port: 80,
path: '/',
agent, // possible but not all that useful.
}, (res) => {
// ...
});
This approach gives you full control over the fetch handler while still leveraging Node.js HTTP servers for request processing.

return new Response('ok');
}
}
:::note
Failing to call `close()` on an HTTP server may result in the server persisting until the worker is destroyed. In most cases, this is not an issue since servers typically live for the lifetime of the worker. However, if you need to create multiple servers during a worker's lifetime or want explicit lifecycle control (such as in test scenarios), call `close()` when you're done with the server, or use [explicit resource management](https://v8.dev/features/explicit-resource-management).
:::

## Server

An implementation of the Node.js [`http.Server`](https://nodejs.org/docs/latest/api/http.html#class-httpserver) class.

The `Server` class represents an HTTP server and provides methods for handling incoming requests. It extends the Node.js `EventEmitter` class and can be used to create custom server implementations.

When using `httpServerHandler`, the port number specified in `server.listen()` acts as a routing key rather than an actual network port. The handler uses this port to determine which HTTP server instance should handle incoming requests, allowing multiple servers to coexist within the same Worker by using different port numbers for identification. Using a port value of `0` (or `null` or `undefined`) will result in a random port number being assigned.

```js
import { Server } from "node:http";
import { httpServerHandler } from "cloudflare:node";

const server = new Server((req, res) => {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ message: "Hello from HTTP Server!" }));
});

server.listen(8080);
export default httpServerHandler({ port: 8080 });
```

The following differences exist between the Workers implementation and Node.js:

- Connection management methods such as `closeAllConnections()` and `closeIdleConnections()` are not implemented
- Only `listen()` variants with a port number or no parameters are supported: `listen()`, `listen(0, callback)`, `listen(callback)`, etc. For reference, see the [Node.js documentation](https://nodejs.org/docs/latest/api/net.html#serverlisten).
- The following server options are not supported: `maxHeaderSize`, `insecureHTTPParser`, `keepAliveTimeout`, `connectionsCheckingInterval`

## ServerResponse

An implementation of the Node.js [`http.ServerResponse`](https://nodejs.org/docs/latest/api/http.html#class-httpserverresponse) class.

The `ServerResponse` class represents the server-side response object that is passed to request handlers. It provides methods for writing response headers and body data, and extends the Node.js `Writable` stream class.

```js
import { createServer, ServerResponse } from "node:http";
import { httpServerHandler } from "cloudflare:node";
import { ok } from "node:assert";

const server = createServer((req, res) => {
ok(res instanceof ServerResponse);

// Set multiple headers at once
res.writeHead(200, {
"Content-Type": "application/json",
"X-Custom-Header": "Workers-HTTP",
});

// Stream response data
res.write('{"data": [');
res.write('{"id": 1, "name": "Item 1"},');
res.write('{"id": 2, "name": "Item 2"}');
res.write("]}");

// End the response
res.end();
});

export default httpServerHandler(server);
```

The following methods and features are not supported in the Workers implementation:

- `assignSocket()` and `detachSocket()` methods are not available
- Trailer headers are not supported
- `writeContinue()` and `writeEarlyHints()` methods are not available
- 1xx responses in general are not supported

## Other differences between Node.js and Workers implementation of `node:http`

Because the Workers implementation of `node:http` is a wrapper around the global `fetch` API, there are some differences in behavior and limitations compared to a standard Node.js environment:

* `Connection` headers are not used. Workers will manage connections automatically.
* `Content-Length` headers will be handled the same way as in the `fetch` API. If a body is provided, the header will be set automatically and manually set values will be ignored.
* `Expect: 100-continue` headers are not supported.
* Trailing headers are not supported.
* The `'continue'` event is not supported.
* The `'information'` event is not supported.
* The `'socket'` event is not supported.
* The `'upgrade'` event is not supported.
* Gaining direct access to the underlying `socket` is not supported.
- `Connection` headers are not used. Workers will manage connections automatically.
- `Content-Length` headers will be handled the same way as in the `fetch` API. If a body is provided, the header will be set automatically and manually set values will be ignored.
- `Expect: 100-continue` headers are not supported.
- Trailing headers are not supported.
- The `'continue'` event is not supported.
- The `'information'` event is not supported.
- The `'socket'` event is not supported.
- The `'upgrade'` event is not supported.
- Gaining direct access to the underlying `socket` is not supported.
Loading
Loading