# New Project

## [Web Server](https://docs.deno.com/runtime/fundamentals/http_server/)

Deno has a built in HTTP server API that allows you to write `HTTP/1.1` and `HTTP/2` servers.

### Starting the project

```bash
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

{% hint style="info" %}
`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.
{% endhint %}

{% hint style="warning" %}
The HTTP server has built in automatic compression of response bodies. *(Supporting* `gzip` *and* `brotli` *compression)*

Check some conditions for this automatic compression [here](https://docs.deno.com/runtime/fundamentals/http_server/#automatic-body-compression).
{% endhint %}

#### Simple content

{% hint style="info" %}
By default Deno will listen on port `8000`.
{% endhint %}

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

{% hint style="warning" %}
`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.
{% endhint %}

For `HTTPS` make sure to add two more parameters.

```typescript
Deno.serve({
    port: 443,
    cert: Deno.readTextFileSync("./cert.pem"),
    key: Deno.readTextFileSync("./key.pem"),
}, handler);
```

#### Streaming content

Check an example [here](https://docs.deno.com/runtime/fundamentals/http_server/#responding-with-a-stream).

#### [Websockets](https://docs.deno.com/runtime/fundamentals/http_server/#serving-websockets)

Deno can upgrade incoming HTTP requests to a WebSocket.

{% hint style="danger" %}
Note that WebSockets are only supported on `HTTP/1.1` for now.
{% endhint %}

### Running

{% hint style="warning" %}
Don't forget to give the `--allow-net` permissions.
{% endhint %}

```bash
deno run --allow-net server.ts
```
