Enabling CORS and HTTPS

Learn how to add a CORS protection layer in a Deno application.

We'll cover the following

CORS protection and HTTPS support are two things considered critical in any running production application. This lesson will explain how can we add them to the application that we’re building.

There are many other security practices that can be added to any API. Because those aren’t Deno specific, we decided to focus on these two elements.

We’ll begin by learning about CORS and how can we leverage Oak and the middleware function feature we know in order to do it. Then, we’ll learn how can we also use a self-signed certificate and make our API handle secure HTTP connections.

Let’s go, starting with CORS.

Enabling CORS

CORS is a mechanism that enables a server to indicate to browsers which origins they should allow resource loading from. When the application is running on the same domain as the API, CORS is not even necessary because the name directly makes explicit.

Here is the quote from Mozilla Developer Network (MDN) explaining CORS:

“Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any other origins (domain, protocol, or port) than its own from which a browser should permit loading of resources. CORS also relies on a mechanism by which browsers make a ‘preflight’ request to the server hosting the cross-origin resource, in order to check that the server will permit the actual request. In that preflight, the browser sends headers that indicate the HTTP method and headers that will be used in the actual request.”

Get hands-on with 1200+ tech skills courses.