On this page
Writing an HTTP Server
HTTP servers are the backbone of the web, allowing you to access websites,download files, and interact with web services. They listen for incomingrequests from clients (like web browsers) and send back responses.
When you build your own HTTP server, you have complete control over its behaviorand can tailor it to your specific needs. You may be using it for localdevelopment, to serve your HTML, CSS, and JS files, or building a REST API -having your own server lets you define endpoints, handle requests and managedata.
Deno's built-in HTTP serverJump to heading
Deno has a built in HTTP server API that allows you to write HTTP servers. TheDeno.serve
API supportsHTTP/1.1 and HTTP/2.
A "Hello World" serverJump to heading
TheDeno.serve
function takes a handler function that will be called for eachincoming request, and is expected to return a response (or a promise resolvingto a response).
Here is an example of a server that returns a "Hello, World!" response for eachrequest:
Deno.serve((_req)=>{returnnewResponse("Hello, World!");});
The handler can also return aPromise<Response>
, which means it can be anasync
function.
To run this server, you can use thedeno run
command:
deno run --allow-net server.ts
There are many more examples of usingDeno.serve
in theExamples collection.
Listening on a specific portJump to heading
By defaultDeno.serve
will listen on port8000
, but this can be changed bypassing in a port number in options bag as the first or second argument:
// To listen on port 4242.Deno.serve({port:4242}, handler);// To listen on port 4242 and bind to 0.0.0.0.Deno.serve({port:4242,hostname:"0.0.0.0"}, handler);
Inspecting the incoming requestJump to heading
Most servers will not answer with the same response for every request. Insteadthey will change their answer depending on various aspects of the request: theHTTP method, the headers, the path, or the body contents.
The request is passed in as the first argument to the handler function. Here isan example showing how to extract various parts of the request:
Deno.serve(async(req)=>{console.log("Method:", req.method);const url=newURL(req.url);console.log("Path:", url.pathname);console.log("Query parameters:", url.searchParams);console.log("Headers:", req.headers);if(req.body){const body=await req.text();console.log("Body:", body);}returnnewResponse("Hello, World!");});
Be aware that thereq.text()
call can fail if the user hangs up the connectionbefore the body is fully received. Make sure to handle this case. Do note thiscan happen in all methods that read from the request body, such asreq.json()
,req.formData()
,req.arrayBuffer()
,req.body.getReader().read()
,req.body.pipeTo()
, etc.
Responding with real dataJump to heading
Most servers do not respond with "Hello, World!" to every request. Instead theymight respond with different headers, status codes, and body contents (even bodystreams).
Here is an example of returning a response with a 404 status code, a JSON body,and a custom header:
Deno.serve((req)=>{const body=JSON.stringify({ message:"NOT FOUND"});returnnewResponse(body,{ status:404, headers:{"content-type":"application/json; charset=utf-8",},});});
Responding with a streamJump to heading
Response bodies can also be streams. Here is an example of a response thatreturns a stream of "Hello, World!" repeated every second:
Deno.serve((req)=>{let timer:number;const body=newReadableStream({asyncstart(controller){ timer=setInterval(()=>{ controller.enqueue("Hello, World!\n");},1000);},cancel(){clearInterval(timer);},});returnnewResponse(body.pipeThrough(newTextEncoderStream()),{ headers:{"content-type":"text/plain; charset=utf-8",},});});
Note thecancel
function above. This is called when the client hangs up theconnection. It is important to make sure that you handle this case, otherwisethe server will keep queuing up messages forever, and eventually run out ofmemory.
Be aware that the response body stream is "cancelled" when the client hangs upthe connection. Make sure to handle this case. This can surface itself as anerror in awrite()
call on aWritableStream
object that is attached to theresponse bodyReadableStream
object (for example through aTransformStream
).
HTTPS supportJump to heading
To use HTTPS, pass two extra arguments in the options:cert
andkey
. Theseare contents of the certificate and key files, respectively.
Deno.serve({port:443,cert: Deno.readTextFileSync("./cert.pem"),key: Deno.readTextFileSync("./key.pem"),}, handler);
To use HTTPS, you will need a valid TLS certificate and a private key for yourserver.
HTTP/2 supportJump to heading
HTTP/2 support is "automatic" when using the HTTP server APIs with Deno. Youjust need to create your server, and it will handle HTTP/1 or HTTP/2 requestsseamlessly.
HTTP/2 is also supported over cleartext with prior knowledge.
Automatic body compressionJump to heading
The HTTP server has built in automatic compression of response bodies. When aresponse is sent to a client, Deno determines if the response body can be safelycompressed. This compression happens within the internals of Deno, so it is fastand efficient.
Currently Deno supports gzip and brotli compression. A body is automaticallycompressed if the following conditions are true:
- The request has an
Accept-Encoding
header which indicates the requester supportsbr
for Brotli orgzip
. Denowill respect the preference of thequality valuein the header. - The response includes a
Content-Type
which is considered compressible. (The list is derived fromjshttp/mime-db
withthe actual listin the code.) - The response body is greater than 64 bytes.
When the response body is compressed, Deno will set theContent-Encoding
header to reflect the encoding, as well as ensure theVary
header is adjustedor added to indicate which request headers affected the response.
In addition to the logic above, there are a few reasons why a responsewon’tbe compressed automatically:
- The response contains a
Content-Encoding
header. This indicates your serverhas done some form of encoding already. - The response contains a
Content-Range
header. This indicates that your server is responding to a range request,where the bytes and ranges are negotiated outside of the control of theinternals to Deno. - The response has a
Cache-Control
header which contains ano-transform
value. This indicates that your server doesn’t want Deno or any downstreamproxies to modify the response.
Serving WebSocketsJump to heading
Deno can upgrade incoming HTTP requests to a WebSocket. This allows you tohandle WebSocket endpoints on your HTTP servers.
To upgrade an incomingRequest
to a WebSocket you use theDeno.upgradeWebSocket
function. This returns an object consisting of aResponse
and a web standardWebSocket
object. The returned response shouldbe used to respond to the incoming request.
Because the WebSocket protocol is symmetrical, theWebSocket
object isidentical to the one that can be used for client side communication.Documentation for it can be foundon MDN.
Deno.serve((req)=>{if(req.headers.get("upgrade")!="websocket"){returnnewResponse(null,{ status:426});}const{ socket, response}= Deno.upgradeWebSocket(req); socket.addEventListener("open",()=>{console.log("a client connected!");}); socket.addEventListener("message",(event)=>{if(event.data==="ping"){ socket.send("pong");}});return response;});
The connection the WebSocket was created on can not be used for HTTP trafficafter a WebSocket upgrade has been performed.
Note that WebSockets are only supported on HTTP/1.1 for now.
Default fetch exportJump to heading
Another way to create an HTTP server in Deno is by exporting a defaultfetch
function.The fetch API initiates an HTTP request toretrieve data from across a network and is built into the Deno runtime.
exportdefault{fetch(request){const userAgent= request.headers.get("user-agent")||"Unknown";returnnewResponse(`User Agent:${userAgent}`);},} satisfies Deno.ServeDefaultExport;
You can run this file with thedeno serve
command:
deno serve server.ts
The server will start and display a message in the console. Open your browserand navigate tohttp://localhost:8000/ to see theuser-agent information.
TheDeno.ServeDefaultExport
interface defines the structure for default exports that can be used with thedeno serve
command. To ensure your code is type-checked properly, make sure toaddsatisfies Deno.ServeDefaultExport
to theexport default { ... }
.
Building on these examplesJump to heading
You will likely want to expand on these examples to create more complex servers.Deno recommends usingOak for building web servers.Oak is a middleware framework for Deno's HTTP server, designed to be expressiveand easy to use. It provides a simple way to create web servers with middlewaresupport. Check out theOak documentation forexamples of how to define routes.