Simple HTTP web server
Concepts
- Use Deno’s integrated HTTP server to run your own web server.
Overview
With just a few lines of code you can run your own HTTP web server with control over the response status, request headers and more.
Sample web server
In this example, the user-agent of the client is returned to the client:
webserver.ts:
1. // Start listening on port 8080 of localhost.
2. const server = Deno.listen({ port: 8080 });
3. console.log(`HTTP webserver running. Access it at: http://localhost:8080/`);
5. // Connections to the server will be yielded up as an async iterable.
6. for await (const conn of server) {
7. // In order to not be blocking, we need to handle each connection individually
8. // without awaiting the function
9. serveHttp(conn);
10. }
12. async function serveHttp(conn: Deno.Conn) {
13. // This "upgrades" a network connection into an HTTP connection.
14. const httpConn = Deno.serveHttp(conn);
15. // Each request sent over the HTTP connection will be yielded as an async
16. // iterator from the HTTP connection.
17. for await (const requestEvent of httpConn) {
18. // The native HTTP server uses the web standard `Request` and `Response`
19. // objects.
20. const body = `Your user-agent is:\n\n${
21. requestEvent.request.headers.get(
22. "user-agent",
23. ) ?? "Unknown"
24. }`;
25. // The requestEvent's `.respondWith()` method is how we send the response
26. // back to the client.
27. requestEvent.respondWith(
28. new Response(body, {
29. status: 200,
30. }),
31. );
32. }
33. }
Then run this with:
1. deno run --allow-net webserver.ts
Then navigate to http://localhost:8080/ in a browser.
Using the std/http library
ℹ️ Since the stabilization of native HTTP bindings in
^1.13.x,std/httpnow supports both a native HTTP server and legacy JavaScript HTTP server from^0.107.0. The legacy server module is now deprecated, and is planned to be removed in a future release.
webserver.ts:
1. import { listenAndServe } from "https://deno.land/std@$STD_VERSION/http/server.ts";
3. const addr = ":8080";
5. const handler = (request: Request): Response => {
6. let body = "Your user-agent is:\n\n";
7. body += request.headers.get("user-agent") || "Unknown";
9. return new Response(body, { status: 200 });
10. };
12. console.log(`HTTP webserver running. Access it at: http://localhost:8080/`);
13. await listenAndServe(addr, handler);
Then run this with:
1. deno run --allow-net webserver.ts
webserver_legacy.ts
1. import { serve } from "https://deno.land/std@$STD_VERSION/http/server_legacy.ts";
3. const server = serve({ port: 8080 });
4. console.log(`HTTP webserver running. Access it at: http://localhost:8080/`);
6. for await (const request of server) {
7. let body = "Your user-agent is:\n\n";
8. body += request.headers.get("user-agent") || "Unknown";
9. request.respond({ status: 200, body });
10. }
Then run this with:
1. deno run --allow-net webserver_legacy.ts
