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

HTTP/2 support is "automatic" when using the HTTP server APIs with Deno.

You just need to create your server, and it will handle HTTP/1 or HTTP/2 requests seamlessly.

Simple content

By default Deno will listen on port 8000.

// 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",
        },
    });
});

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.

Running

deno run --allow-net server.ts

Last updated