Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 37 ยท HTTP Servers

HTTP Servers with Deno.serve

Build your first HTTP server in Deno with Deno.serve. Learn handlers, Request and Response, ports, permissions, graceful shutdown and how to test a handler without a network.

A server in Deno is a function. You give Deno.serve a function that receives a standard Request and returns a standard Response (or a promise of one), and the runtime does everything else: listening on a port, parsing HTTP, running many requests at once and writing the reply back. There is no framework to install and no http.createServer callback with req and res objects. If you know the browser's fetch API, you already know the vocabulary.

This lesson covers the handler contract, the options you will use every day, how to stop a server cleanly, and a trick that makes servers easy to test: because a handler is just a function from Request to Response, you can call it directly without opening a port.

Deno itself does not run on this site, so the Deno commands and Deno.* code below are read-only. The runnable examples use plain Node 24 code that uses the same Request and Response classes (they are web standards) to show exactly the same handler logic. Each one is labelled as a stand-in.

Your first server

TypeScript
// server.ts
Deno.serve((_req: Request) => {
  return new Response("Hello from Deno!");
});

Run it with the network permission:

Terminal
deno run --allow-net server.ts
# Listening on http://0.0.0.0:8000/ (http://localhost:8000/)

Open http://localhost:8000 and you see the text. Three things are worth noticing. The default port is 8000. The server listens on all interfaces unless you say otherwise. And without --allow-net Deno stops at the first line with a permission prompt (see permissions in the Modules and Permissions chapter for the full model).

The handler can be async, and it can read the request before it answers:

TypeScript
Deno.serve(async (req) => {
  const url = new URL(req.url);
  if (url.pathname === "/ping") {
    return new Response("pong");
  }
  const name = url.searchParams.get("name") ?? "stranger";
  return new Response(`Hello, ${name}!`);
});

req.url is an absolute URL string, so new URL(req.url) gives you pathname, searchParams and hash for free.

The handler contract

Part What it is
Input 1 Request (method, url, headers, body, signal)
Input 2 info with remoteAddr (client IP and port) and completed
Output Response, or a Promise<Response>
Errors An uncaught throw becomes a 500 Internal Server Error

Whatever you return must be a real Response. Returning a string or an object is a mistake and produces a 500, so build the response explicitly. Helpers make the common cases short:

TypeScript
return Response.json({ ok: true });                 // application/json
return new Response(null, { status: 204 });         // no content
return Response.redirect("https://example.com", 302);
return new Response("Not found", { status: 404 });

The second argument, info, tells you who is calling:

TypeScript
Deno.serve((req, info) => {
  const ip = info.remoteAddr.hostname;
  return new Response(`You are ${ip}`);
});

Behind a proxy or CDN that address is the proxy's, so read X-Forwarded-For only if you trust the proxy that sets it.

Testing a handler without a network

Because a handler is a plain function, you can call it from a test. Build a Request, call the function, and inspect the Response. This is fast, needs no port and no permissions. The stand-in below does exactly that in Node 24, using the same classes Deno uses.

Node.js Calling a handler directly (Node stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice the content types. A string body gets text/plain;charset=UTF-8, Response.json gets application/json. Deno picks these for you when you do not set the header.

Options: port, hostname, signal

The first argument can be an options object when you need more control:

TypeScript
const controller = new AbortController();

const server = Deno.serve(
  {
    port: 3000,
    hostname: "127.0.0.1",
    signal: controller.signal,
    onListen: ({ hostname, port }) => {
      console.log(`Ready on http://${hostname}:${port}`);
    },
    onError: (error) => {
      console.error(error);
      return new Response("Something went wrong", { status: 500 });
    },
  },
  (req) => new Response("ok"),
);
  • port and hostname: use 127.0.0.1 for development so the server is not reachable from the network. Use Deno.env.get("PORT") in production, where the platform tells you the port.
  • signal: aborting the controller stops the server.
  • onListen: replaces the default "Listening on..." line.
  • onError: turns an exception thrown by your handler into a response you choose. Without it Deno logs the error and sends a plain 500.

Deno.serve returns an HttpServer object. await server.finished waits until the server has stopped, and await server.shutdown() stops it gracefully: it stops accepting connections and waits for the running requests to finish.

TypeScript
Deno.addSignalListener("SIGINT", async () => {
  await server.shutdown();
  console.log("bye");
  Deno.exit(0);
});

TLS is a pair of options too: pass cert and key (PEM strings) and the same handler serves HTTPS. See Deploy and Docker for why most production setups terminate TLS in front of the app instead.

A real server, end to end

This stand-in builds a tiny serve() on top of node:http with the same shape as Deno.serve, then talks to it with fetch. It is only a teaching device: in Deno you simply call the real thing.

Node.js A server and a client (Node stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The visits counter lives in a module-level variable. That works while the process lives, but remember that on a platform like Deno Deploy several instances may run at once, and none of them shares memory. Shared state belongs in a database or Deno KV.

Common mistakes

  • Returning something that is not a Response. return "hi" fails. Wrap it: return new Response("hi").
  • Forgetting await on the body. req.json(), req.text() and req.formData() return promises.
  • Reading a body twice. A body is a stream and can be consumed once. Call req.clone() first if two readers need it.
  • Binding to 0.0.0.0 on a laptop and exposing a dev server to the whole Wi-Fi network.
  • No --allow-net. Deno prompts in a terminal and exits with an error in CI. Be explicit: --allow-net=0.0.0.0:8000 limits the permission to the address you serve.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What must a handler passed to Deno.serve return?

    The handler returns a standard Response (or a Promise<Response>). Strings and plain objects are not accepted.
  2. 2. What is the default port of Deno.serve?

    When you do not pass a port, Deno.serve listens on 8000.
  3. 3. How can you unit test a handler without opening a network port?

    A handler is an ordinary function from Request to Response, so a test can build a Request and call it directly.
  4. 4. What does server.shutdown() do?

    shutdown() is a graceful stop: no new connections, running requests are allowed to complete.

Summary

  • Deno.serve(handler) runs an HTTP server; the handler maps a Request to a Response.
  • The second handler argument has remoteAddr; options add port, hostname, signal, onListen, onError and TLS.
  • Uncaught errors become a 500 unless onError replaces the response.
  • server.shutdown() stops gracefully; server.finished resolves when it is done.
  • Handlers are plain functions, so test them by calling them with a Request.
  • Run with --allow-net, ideally narrowed to the address you serve.

Next: Requests and Responses