New Project
Deno has a built in HTTP server API that allows you to write HTTP/1.1
and HTTP/2
servers.
Starting the project
deno init <project_name>
VSCode
Inside VSCode you may want to execute:
Deno: Initialize Workspace Configuration
This will create a .vscode
on the project to enable Deno extension to work.
Serving content
The HTTP server has built in automatic compression of response bodies. (Supporting gzip
and brotli
compression)
Check some conditions for this automatic compression here.
Simple content
// To listen on port 4242 and bind to 0.0.0.0.
Deno.serve({ port: 4242, hostname: "0.0.0.0" }, (req) => {
console.log("Method:", req.method);
const url = new URL(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);
}
// Responding a string only
return new Response('Hello World.');
const data = JSON.stringify({ id: 1, name: 'Marco', ... });
return new Response(data, {
status: 200,
headers: {
"content-type": "application/json; charset=utf-8",
},
});
});
req.text()
call and ALL other methods that read from the Request Body can fail if the user hangs up the connection before the body is fully received.
Make sure to handle this case.
For HTTPS
make sure to add two more parameters.
Deno.serve({
port: 443,
cert: Deno.readTextFileSync("./cert.pem"),
key: Deno.readTextFileSync("./key.pem"),
}, handler);
Streaming content
Check an example here.
Deno can upgrade incoming HTTP requests to a WebSocket.
Note that WebSockets are only supported on HTTP/1.1
for now.
Running
Don't forget to give the --allow-net
permissions.
deno run --allow-net server.ts
Last updated