Deno nuggets: New HTTP server

Mayank C
Tech Tonic

--

This article is a part of the Deno nuggets series, where each article attempts to suggest a pointed solution to a specific question that can be read in less than a minute. There is no ordering of nuggets.

Problem

How to write a simple ‘Hello world’ program with Deno’s new HTTP server?

> curl http://localhost:3000
Hello world!

Solution

With release v1.25, for performance reasons, Deno has changed its core HTTP server. The new HTTP server is called flash. This server is claimed to be much faster than the old one. In fact, Deno authors see this as the fastest web server JavaScript has ever seen.

Being new, the flash HTTP server is still under the unstable umbrella. The flash server API Deno.serve is a part of the core runtime, therefore no imports are required. The Deno.serve API takes two inputs:

  • Request handler
  • Additional options like port, certs, etc.

The handler interface is the same: A Request object is given to the handler and a Response object is expected.

The following is the one-line code of a Hello world server using Deno’s new HTTP server:

Deno.serve((req: Request) => new Response("Hello world!"), { port: 3000 });

Let’s test it out:

> deno run --allow-net --unstable app.ts 
Listening on http://127.0.0.1:3000/
> curl http://localhost:3000 -v
* Connected to localhost (127.0.0.1) port 3000 (#0)
> GET / HTTP/1.1
> Host: localhost:3000
> User-Agent: curl/7.79.1
> Accept: */*
>
< HTTP/1.1 200 OK
< Date: Sat, 27 Aug 2022 00:49:22 GMT
< Content-Type: text/plain;charset=UTF-8
< Content-Length: 12
<
Hello world!

--

--