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/`);
  4. // Connections to the server will be yielded up as an async iterable.
  5. for await (const conn of server) {
  6. // In order to not be blocking, we need to handle each connection individually
  7. // without awaiting the function
  8. serveHttp(conn);
  9. }
  10. async function serveHttp(conn: Deno.Conn) {
  11. // This "upgrades" a network connection into an HTTP connection.
  12. const httpConn = Deno.serveHttp(conn);
  13. // Each request sent over the HTTP connection will be yielded as an async
  14. // iterator from the HTTP connection.
  15. for await (const requestEvent of httpConn) {
  16. // The native HTTP server uses the web standard `Request` and `Response`
  17. // objects.
  18. const body = `Your user-agent is:\n\n${requestEvent.request.headers.get(
  19. "user-agent",
  20. ) ?? "Unknown"}`;
  21. // The requestEvent's `.respondWith()` method is how we send the response
  22. // back to the client.
  23. requestEvent.respondWith(
  24. new Response(body, {
  25. status: 200,
  26. }),
  27. );
  28. }
  29. }

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 stabilization of native HTTP server in 1.13, usage of std/http is discouraged. The module is planned to be deprecated in the future releases.

webserver.ts:

  1. import { serve } from "https://deno.land/std@$STD_VERSION/http/server.ts";
  2. const server = serve({ port: 8080 });
  3. console.log(`HTTP webserver running. Access it at: http://localhost:8080/`);
  4. for await (const request of server) {
  5. let bodyContent = "Your user-agent is:\n\n";
  6. bodyContent += request.headers.get("user-agent") || "Unknown";
  7. request.respond({ status: 200, body: bodyContent });
  8. }

Then run this with:

  1. deno run --allow-net webserver.ts