You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: src/content/docs/workers/runtime-apis/nodejs/http.mdx
+47-1Lines changed: 47 additions & 1 deletion
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -228,7 +228,53 @@ server.listen(8080);
228
228
exportdefaulthttpServerHandler({ port:8080 });
229
229
```
230
230
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.
231
+
## Node.js integration
232
+
233
+
### httpServerHandler
234
+
235
+
The `httpServerHandler` function integrates Node.js HTTP servers with the Cloudflare Workers request model. It supports two API patterns:
// Pass server directly (simplified) - automatically calls listen() if needed
246
+
exportdefaulthttpServerHandler(server);
247
+
248
+
// Or use port-based routing for multiple servers
249
+
server.listen(8080);
250
+
exportdefaulthttpServerHandler({ port:8080 });
251
+
```
252
+
253
+
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.
254
+
255
+
### handleAsNodeRequest
256
+
257
+
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:
This approach gives you full control over the fetch handler while still leveraging Node.js HTTP servers for request processing.
232
278
233
279
:::note
234
280
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).
0 commit comments