Skip to content

Commit 68b9d8f

Browse files
committed
add node:http and node:https documentation
1 parent e8c917e commit 68b9d8f

File tree

3 files changed

+342
-153
lines changed

3 files changed

+342
-153
lines changed

src/content/docs/workers/runtime-apis/nodejs/http.mdx

Lines changed: 213 additions & 85 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,52 @@ pcx_content_type: configuration
33
title: http
44
---
55

6-
import { Render } from "~/components"
6+
import { Render } from "~/components";
77

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

10+
## Compatibility flags
11+
12+
### Client-side methods
13+
14+
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.
15+
16+
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`:
17+
18+
```toml
19+
compatibility_flags = ["nodejs_compat", "enable_nodejs_http_modules"]
20+
```
21+
22+
### Server-side methods
23+
24+
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.
25+
26+
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`:
27+
28+
```toml
29+
compatibility_flags = ["nodejs_compat", "enable_nodejs_http_server_modules"]
30+
```
31+
32+
To use both client-side and server-side methods, enable both flags:
33+
34+
```toml
35+
compatibility_flags = ["nodejs_compat", "enable_nodejs_http_modules", "enable_nodejs_http_server_modules"]
36+
```
37+
38+
## Agent
39+
40+
An implementation of the Node.js [`http.Agent`](https://nodejs.org/docs/latest/api/http.html#class-httpagent) class.
41+
42+
An [Agent](https://nodejs.org/docs/latest/api/http.html#class-httpagent) 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.
43+
44+
```js
45+
import { Agent } from "node:http";
46+
import { strictEqual } from "node:assert";
47+
48+
const agent = new Agent();
49+
strictEqual(agent.protocol, "http:");
50+
```
51+
1052
## get
1153

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

2062
```js
21-
import { get } from 'node:http';
63+
import { get } from "node:http";
64+
import { strictEqual, ok } from "node:assert";
2265

2366
export default {
2467
async fetch() {
2568
const { promise, resolve, reject } = Promise.withResolvers();
26-
get('http://example.org', (res) => {
27-
let data = '';
28-
res.setEncoding('utf8');
29-
res.on('data', (chunk) => {
69+
get("http://docs.cloudflare.com/robots.txt", (res) => {
70+
// requests to http://docs.cloudflare.com get redirected to their https counterpart.
71+
strictEqual(res.statusCode, 301);
72+
let data = "";
73+
res.setEncoding("utf8");
74+
res.on("data", (chunk) => {
3075
data += chunk;
3176
});
32-
res.on('end', () => {
77+
res.once("error", reject);
78+
res.on("end", () => {
79+
ok(data.includes("301 Moved Permanently"));
3380
resolve(new Response(data));
3481
});
35-
res.on('error', reject);
36-
}).on('error', reject);
82+
});
3783
return promise;
38-
}
39-
}
84+
},
85+
};
4086
```
4187

4288
The implementation of `get` in Workers is a wrapper around the global
@@ -49,7 +95,7 @@ when the handler returns.
4995

5096
## request
5197

52-
An implementation of the Node.js [`http.request'](https://nodejs.org/docs/latest/api/http.html#httprequesturl-options-callback) method.
98+
An implementation of the Node.js [`http.request`](https://nodejs.org/docs/latest/api/http.html#httprequesturl-options-callback) method.
5399

54100
The `request` method creates an HTTP request with customizable options like method, headers, and body. It provides full control over the request configuration and returns a Node.js [stream.Writable](https://developers.cloudflare.com/workers/runtime-apis/nodejs/streams/) for sending request data.
55101

@@ -58,34 +104,42 @@ fetch or similar handler. Outside of such a handler, attempts to use `request` w
58104
an error.
59105

60106
```js
61-
import { get } from 'node:http';
107+
import { request } from "node:http";
108+
import { strictEqual, ok } from "node:assert";
62109

63110
export default {
64111
async fetch() {
65112
const { promise, resolve, reject } = Promise.withResolvers();
66-
get({
67-
method: 'GET',
68-
protocol: 'http:',
69-
hostname: 'example.org',
70-
path: '/'
71-
}, (res) => {
72-
let data = '';
73-
res.setEncoding('utf8');
74-
res.on('data', (chunk) => {
75-
data += chunk;
76-
});
77-
res.on('end', () => {
78-
resolve(new Response(data));
79-
});
80-
res.on('error', reject);
81-
}).on('error', reject)
82-
.end();
113+
const req = request(
114+
{
115+
method: "GET",
116+
protocol: "http:",
117+
hostname: "docs.cloudflare.com",
118+
path: "/",
119+
},
120+
(res) => {
121+
// requests to http://docs.cloudflare.com get redirected to their https counterpart.
122+
strictEqual(res.statusCode, 301);
123+
124+
let data = "";
125+
res.setEncoding("utf8");
126+
res.on("data", (chunk) => {
127+
data += chunk;
128+
});
129+
res.once("error", reject);
130+
res.on("end", () => {
131+
ok(data.includes("301 Moved Permanently"));
132+
resolve(new Response(data));
133+
});
134+
},
135+
);
136+
req.end();
83137
return promise;
84-
}
85-
}
138+
},
139+
};
86140
```
87141

88-
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:
142+
The following options passed to the `request` method are not supported due to differences in the Cloudflare Workers implementation of the `node:http` module:
89143

90144
- `maxHeaderSize`
91145
- `insecureHTTPParser`
@@ -95,80 +149,154 @@ The following options passed to the `request` (and `get`) method are not support
95149

96150
## OutgoingMessage
97151

98-
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/).
152+
An implementation of the Node.js [`http.OutgoingMessage`](https://nodejs.org/docs/latest/api/http.html#class-httpoutgoingmessage) class.
99153

100-
```js
101-
import { OutgoingMessage } from 'node:http';
154+
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).
102155

103-
export default {
104-
async fetch() {
105-
// ...
106-
const res = new OutgoingMessage();
107-
res.writeHead(200, { 'Content-Type': 'text/plain' });
108-
res.write('Hello, World!');
109-
res.end();
110-
// ...
111-
}
112-
}
113-
```
156+
Both `ClientRequest` and `ServerResponse` both extend from and inherit from `OutgoingMessage`.
114157

115158
## IncomingMessage
116159

117-
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.
160+
An implementation of the Node.js [`http.IncomingMessage`](https://nodejs.org/docs/latest/api/http.html#class-httpincomingmessage) class.
161+
162+
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.
118163

119164
```js
120-
import { get, IncomingMessage } from 'node:http';
121-
import { ok, strictEqual } from 'node:assert';
165+
import { get, IncomingMessage } from "node:http";
166+
import { ok, strictEqual } from "node:assert";
122167

123168
export default {
124169
async fetch() {
125-
// ...
126-
get('http://example.org', (res) => {
170+
const { promise, resolve } = Promise.withResolvers();
171+
get("http://docs.cloudflare.com", (res) => {
172+
strictEqual(res.statusCode, 301);
127173
ok(res instanceof IncomingMessage);
174+
resolve(new Response("ok"));
128175
});
129-
// ...
130-
}
131-
}
176+
return promise;
177+
},
178+
};
132179
```
133180

134-
## Agent
181+
The Workers implementation includes a `cloudflare` property on `IncomingMessage` objects:
182+
183+
```js
184+
import { createServer } from "node:http";
185+
import { httpServerHandler } from "cloudflare:node";
186+
187+
const server = createServer((req, res) => {
188+
console.log(req.cloudflare.cf.country);
189+
console.log(req.cloudflare.cf.ray);
190+
res.write("Hello, World!");
191+
res.end();
192+
});
193+
194+
server.listen(8080);
195+
196+
export default httpServerHandler({ port: 8080 });
197+
```
135198

136-
A partial implementation of the Node.js [`http.Agent'](https://nodejs.org/docs/latest/api/http.html#class-httpagent) class.
199+
The `cloudflare.cf` property contains [Cloudflare-specific request properties](/workers/runtime-apis/request/#incomingrequestcfproperties).
137200

138-
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.
201+
The following differences exist between the Workers implementation and Node.js:
202+
203+
- Trailer headers are not supported
204+
- The `socket` attribute **does not extend from `net.Socket`** and only contains the following properties: `encrypted`, `remoteFamily`, `remoteAddress`, `remotePort`, `localAddress`, `localPort`, and `destroy()` method.
205+
- The following `socket` attributes behave differently than their Node.js counterparts:
206+
- `remoteAddress` will return `127.0.0.1` when ran locally
207+
- `remotePort` will return a random port number between 2^15 and 2^16
208+
- `localAddress` will return the value of request's `host` header if exists. Otherwise, it will return `127.0.0.1`
209+
- `localPort` will return the port number assigned to the server instance
210+
- `req.socket.destroy()` falls through to `req.destroy()`
211+
212+
## createServer
213+
214+
An implementation of the Node.js [`http.createServer`](https://nodejs.org/docs/latest/api/http.html#httpcreateserveroptions-requestlistener) method.
215+
216+
The `createServer` method creates an HTTP server instance that can handle incoming requests.
139217

140218
```js
141-
import { get, Agent } from 'node:http';
142-
import { strictEqual } from 'node:assert';
219+
import { createServer } from "node:http";
220+
import { httpServerHandler } from "cloudflare:node";
143221

144-
export default {
145-
async fetch() {
222+
const server = createServer((req, res) => {
223+
res.writeHead(200, { "Content-Type": "text/plain" });
224+
res.end("Hello from Node.js HTTP server!");
225+
});
146226

147-
const agent = new Agent();
148-
get({
149-
hostname: 'example.org',
150-
port: 80,
151-
path: '/',
152-
agent, // possible but not all that useful.
153-
}, (res) => {
154-
// ...
155-
});
227+
server.listen(8080);
228+
export default httpServerHandler({ port: 8080 });
229+
```
156230

157-
return new Response('ok');
158-
}
159-
}
231+
The `httpServerHandler` function integrates Node.js HTTP servers with the Cloudflare Workers request model. When a request arrives at your Worker, the handler automatically routes it to your Node.js server running on the specified port. Handler is using the specified port to determine which app to route the request to. This bridge allows you to use familiar Node.js server patterns while benefiting from the Workers runtime environment, including automatic scaling, edge deployment, and integration with other Cloudflare services.
232+
233+
:::note
234+
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).
235+
:::
236+
237+
## Server
238+
239+
An implementation of the Node.js [`http.Server`](https://nodejs.org/docs/latest/api/http.html#class-httpserver) class.
240+
241+
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.
242+
243+
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.
244+
245+
```js
246+
import { Server } from "node:http";
247+
import { httpServerHandler } from "cloudflare:node";
248+
249+
const server = new Server((req, res) => {
250+
res.writeHead(200, { "Content-Type": "application/json" });
251+
res.end(JSON.stringify({ message: "Hello from HTTP Server!" }));
252+
});
253+
254+
server.listen(8080);
255+
export default httpServerHandler({ port: 8080 });
160256
```
161257

162-
## Other differences between Node.js and Workers implementation of `node:http`
258+
The following differences exist between the Workers implementation and Node.js:
259+
260+
- Connection management methods such as `closeAllConnections()` and `closeIdleConnections()` are not implemented
261+
- 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).
262+
- The following server options are not supported: `maxHeaderSize`, `insecureHTTPParser`, `keepAliveTimeout`, `connectionsCheckingInterval`
263+
264+
## ServerResponse
265+
266+
An implementation of the Node.js [`http.ServerResponse`](https://nodejs.org/docs/latest/api/http.html#class-httpserverresponse) class.
267+
268+
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.
269+
270+
```js
271+
import { createServer } from "node:http";
272+
import { httpServerHandler } from "cloudflare:node";
273+
274+
const server = createServer((req, res) => {
275+
ok(res instanceof ServerResponse);
276+
277+
// Set multiple headers at once
278+
res.writeHead(200, {
279+
"Content-Type": "application/json",
280+
"X-Custom-Header": "Workers-HTTP",
281+
});
282+
283+
// Stream response data
284+
res.write('{"data": [');
285+
res.write('{"id": 1, "name": "Item 1"},');
286+
res.write('{"id": 2, "name": "Item 2"}');
287+
res.write("]}');
288+
289+
// End the response
290+
res.end();
291+
});
292+
293+
server.listen(8080);
294+
export default httpServerHandler({ port: 8080 });
295+
```
163296
164-
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:
297+
The following methods and features are not supported in the Workers implementation:
165298
166-
* `Connection` headers are not used. Workers will manage connections automatically.
167-
* `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.
168-
* `Expect: 100-continue` headers are not supported.
169-
* Trailing headers are not supported.
170-
* The `'continue'` event is not supported.
171-
* The `'information'` event is not supported.
172-
* The `'socket'` event is not supported.
173-
* The `'upgrade'` event is not supported.
174-
* Gaining direct access to the underlying `socket` is not supported.
299+
- `assignSocket()` and `detachSocket()` methods are not available
300+
- Trailer headers are not supported
301+
- `writeContinue()` and `writeEarlyHints()` methods are not available
302+
- 1xx responses in general are not supported

0 commit comments

Comments
 (0)