Blog

Something more about Cloudflare

Rafał Masiarek Rafał Masiarek
Share

CloudFlare is a very popular tool because underneath the pleasant and intuitive user interface are many features that protect our web application from numerous threats. An additional advantage of Cloudflare is that, through its proxy, it allows you to hide the real IP addresses of the server hosting your site, which also makes it more difficult for a potential attacker to target your site.

But let’s start with the basics, Cloudflare is a DNS address service provider “on steroids”, because as part of maintaining its domain (or more accurately, its DNS zone), it allows the issuance between the application and the visitor of a proxy, an intermediary service that:

  1. It plays the role of a CDN – It has dozens of servers around the world where it can store copies of static files automatically. As a result, a picture of a cat that is served from a server located in Warsaw can load just as quickly in Frankfurt, Dublin, New York or Hong-Kong.
  2. Mediates SSL certificate – since 2017, Google has been very effective in forcing site owners to make their applications accessible over secure HTTPS (with an SSL certificate). Since then, hosting companies have practically offered as standard the possibility of issuing a free SSL certificate for their sites. However, this is not so obvious in the case of dedicated servers or native cloud services, where you have to, in many cases, take care of the correct configuration and automatic renewal of certificates yourself, which are often issued for only 3 months in the free version. In this case, too, CloudFlare can help by taking care of this on its side.
  3. Is a Firewall – It filters traffic that tries to get to the site, it can cut out bots it knows, bad IP addresses, and through its filters we can, in an extreme case, block traffic to our site from a whole specific country (e.g., all IT Administrators’ darlings – China ???? ) or simply limit access to the backend of the store for a few specific IP addresses.

By way of introduction, I wanted to give you, dear reader, an idea of what CloudFlare’s service is in general and why you should use it. However, in this article I would like to introduce “something more from cloudflare”, namely two other services, with which we will run 3 simple sample applications. Static and dynamic without the need to use hosting or another server, and all for free.

Cloudflare page

It is a service through which, without the need for a server or hosting service, we will launch a static site that can act as a business card or portfolio.

In order for CloudFlare Page to work, we need to create a repository on a popular service for developers such as GitHub.com (Cloudflare Pages also supports GitLab however in this article we will limit ourselves to Github due to its popularity).

For the purpose of this article, I created a simple repository, with one static file index.html, which will be our home page. When we have a repository prepared, in the Cloudflare Panel:

Go to the “Pages” subpage and authenticate with GitHub:

We will then be redirected to the GitHub settings where we can grant access to the previously created repository where our index.html is located :

Once approved, it remains to build the site using the “Build” button. In a few minutes, our site will be public, and all we have to do is plug in our domain under the “Custom Domain” tab:

It is worth noting that from now on, CloudFlage Page will respond to every change in the repository and refresh our page after every change in GIT.

Cloudflare Workers

Workers is already a more advanced feature with which we can serve backend applications, written in JavaScripcie or even in C. In this example, we’ll run through CloudFlare Workers’ serverless service a simple API that will return the current IP address in JSON form, and based on that (using CloudFlare’s infrastructure) we’ll determine the country our visitor is from.

First, we need to create a new service in the “Workers” tab from the CloudFlare dashboard and one by one:

2 Select the name of the service,

3. change the starter to HTTP Handler,

4. create a service with the button Create Service.

Thus, we already have a service created, which immediately after creation, under the generated domain serves us “Hello World”.

However, let’s approach the subject more ambitiously. Instead of a welcome to the site, let’s display more useful information. Let’s turn to the editor in this case:

Next, let’s paste the following code:

addEventListener("fetch", (event) => {
  let request = event.request // Request object
  event.respondWith(
    handleRequest(event.request).catch(
      (err) => new Response(err.stack, { status: 500 })
    )
  );
});

async function handleRequest(request) {
  const { pathname } = new URL(request.url);
  const ip = request.headers.get("CF-Connecting-IP")
  const country = request.headers.get("CF-IPCountry")

  return new Response(JSON.stringify({ip, country}), {
    headers: { "Content-Type": "application/json" },
  });
}

And click “Save and deploy”.

As a result, our application begins to return dynamic data:

{
  "ip": "XXX.XX.XX.XX",
  "country": "PL"
}

Dimensional serverless application

In the last example, I would like to demonstrate how to use our backend on the site created on the previously discussed CloudFlare Pages service to create a full-size serverless application divided into backend and frontend. To do this, I created a repository containing an HTML page that, using jQuery, references JSON and irons it into an aesthetically pleasing form:

<body>
    <div class="container"></div>
</body>
<script src="/jquery-3.2.1.min.js"></script>
<script>
    $.getJSON('https://twilight-art-6f49.masiarek.workers.dev', function(data) {
        var text = "<h1>" + data.ip + "</h1><h3>" + data.country + "</h3>"
        $(".container").html(text);
    });
</script>

An example serverless application can be previewed at the indicated address: Example 2

CloudFlare is definitely one of my favorite tools. And are you using Cloudflare? Let us know what you think about it.

Contact

Do you have questions? Get in touch with us