---
title: http · Cloudflare Workers docs
description: To use the HTTP client-side methods (http.get, http.request, etc.),
  you must enable the enable_nodejs_http_modules compatibility flag in addition
  to the nodejs_compat flag.
lastUpdated: 2025-08-26T18:22:59.000Z
chatbotDeprioritize: false
source_url:
  html: https://developers.cloudflare.com/workers/runtime-apis/nodejs/http/
  md: https://developers.cloudflare.com/workers/runtime-apis/nodejs/http/index.md
---

Note

To enable built-in Node.js APIs and polyfills, add the nodejs\_compat compatibility flag to your [Wrangler configuration file](https://developers.cloudflare.com/workers/wrangler/configuration/). This also enables nodejs\_compat\_v2 as long as your compatibility date is 2024-09-23 or later. [Learn more about the Node.js compatibility flag and v2](https://developers.cloudflare.com/workers/configuration/compatibility-flags/#nodejs-compatibility-flag).

## 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`](https://developers.cloudflare.com/workers/configuration/compatibility-flags/) compatibility flag in addition to the [`nodejs_compat`](https://developers.cloudflare.com/workers/runtime-apis/nodejs/) flag.

This flag is automatically enabled for Workers using a [compatibility date](https://developers.cloudflare.com/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`](https://developers.cloudflare.com/workers/runtime-apis/nodejs/) flag.

This flag is automatically enabled for Workers using a [compatibility date](https://developers.cloudflare.com/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.

The `get` method performs a GET request to the specified URL and invokes the callback with the response. It's a convenience method that simplifies making HTTP GET requests without manually configuring request options.

Because `get` is a wrapper around `fetch(...)`, it may be used only within an exported fetch or similar handler. Outside of such a handler, attempts to use `get` will throw an error.

```js
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) => {
        data += chunk;
      });
      res.on("end", () => {
        resolve(new Response(data));
      });
      res.on("error", reject);
    }).on("error", reject);
    return promise;
  },
};
```

The implementation of `get` in Workers is a wrapper around the global [`fetch` API](https://developers.cloudflare.com/workers/runtime-apis/fetch/) and is therefore subject to the same [limits](https://developers.cloudflare.com/workers/platform/limits/).

As shown in the example above, it is necessary to arrange for requests to be correctly awaited in the `fetch` handler using a promise or the fetch may be canceled prematurely when the handler returns.

## request

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

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.

Because `request` is a wrapper around `fetch(...)`, it may be used only within an exported fetch or similar handler. Outside of such a handler, attempts to use `request` will throw an error.

```js
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();
    return promise;
  },
};
```

The following options passed to the `request` (and `get`) method are not supported due to the differences required by Cloudflare Workers implementation of `node:http` as a wrapper around the global `fetch` API:

* `maxHeaderSize`
* `insecureHTTPParser`
* `createConnection`
* `lookup`
* `socketPath`

## OutgoingMessage

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/).

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).

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.

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";


export default {
  async fetch() {
    // ...
    get("http://example.org", (res) => {
      ok(res instanceof IncomingMessage);
    });
    // ...
  },
};
```

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](https://developers.cloudflare.com/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

A partial implementation of the Node.js [\`http.Agent'](https://nodejs.org/docs/latest/api/http.html#class-httpagent) class.

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 { 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 {
  fetch(request) {
    return handleAsNodeRequest(8080, request);
  },
};
```

This approach gives you full control over the fetch handler while still leveraging Node.js HTTP servers for request processing.

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.
