1 of 20
2 of 20
3 of 20
4 of 20
5 of 20
6 of 20
7 of 20
8 of 20
9 of 20
10 of 20
11 of 20
12 of 20
13 of 20
14 of 20
15 of 20
16 of 20
17 of 20
18 of 20
19 of 20
20 of 20

site

doc

blog

success stories

Blog

Simplifying and Accelerating Deliveries with Serverless Functions

Introduction

In an exponentially growing company, we need to ensure deliveries that are increasingly relevant in an ever shorter amount of time. By running Edge Functions we can easily write pieces of code that are crucial to your business, without needing to set up a whole server, security, and all those things we all are familiar with.

Today, Azion’s Marketing team is responsible for all the company’s web pages. There are engineers working together with the team performing the orchestration of the pages. In this post we will look at two important problems solved using serverless JavaScript functions for large scale delivery.

Solved Problems

  • Careers Portal;
  • Sitemap of different projects under the same domain;

Careers Portal

We previously worked with a third party company that generated the data and pages for the career portal, but decided it was time to sharpen the usability and add our own unique style to the design. However, to run it all we required a comprehensive understanding of all the existing structures in place, including:

  • Server;
  • Scalability;
  • Availability;
  • Security;
  • Updates;

With Azion Cells (JavaScript Functions) we have everything configured by default, besides natively running JavaScript code directly at the Edge. Because we have hundreds of servers spread across all Brazilian states we can guarantee scalability. Besides, our function runs as close as possible to the user.

As Azion has a CDN (Content Delivery Network) in its product catalog, we have an obligation to be always available. This automatically solves scalability problems. Because this architecture exists automatically, we have a secure environment against cracker attacks (if you don’t know the difference between hacker and cracker, learn more here), such as DDoS, Path Traverse, and other known attacks.

Have a look at the code below to see an example of JavaScript running at the edge:

A small piece of code that fetches data from anywhere, used to build our Career Portal.

NOTE: The API Key is merely illustrative.

Incredible, right? But it’s not over yet, I’ll tell you right away how we put together our sitemap from different repositories in a single delivery.

Azion.com Sitemap

We could write another post about this part, but I want to show how easy and important it is to use JavaScript on the edge. We are currently using Jekyll to work with SSG in some parts of Azion website, such as:

The domain is the same but the projects are separate, they are separate Jekyll, deploy independently and each one uses a bucket, so we can clean without fear.

To get this all together, each project generates a sitemap.json file. During build the existing urls are written to this json.

The input is something like:

---
# Automated Sitemap
layout: null
---
{%- for page in site.html_pages -%}
    {%- assign index = index | push: page | uniq -%}
{%- endfor -%}
{%- for post in site.posts -%}
    {%- assign index = index | push: post | uniq -%}
{%- endfor -%}
{
    "pt-br": [
    {%- for document in index -%}
        {% if document.permalink_pt-br.size > 0 %}"https://www.azion.com/pt-br{{ document.permalink_pt-br }}"{% if forloop.last != true %},{% endif %}{% endif %}
    {%- endfor -%}
    ],
    "en": [
    {%- for document in index -%}
        {% if document.permalink.size > 0 %}"https://www.azion.com/en{{ document.permalink }}"{% if forloop.last != true %},{% endif %}{% endif %}
    {%- endfor -%}
    ],
    "es": [
    {%- for document in index -%}
        {% if document.permalink_es.size > 0 %}"https://www.azion.com/es{{ document.permalink_es }}"{% if forloop.last != true %},{% endif %}{% endif %}
    {%- endfor -%}
    ],
    "all": [
        {%- for document in index -%}
        {
            {% if document.permalink_pt-br.size  > 0 %}"pt-br": "https://www.azion.com/pt-br{{ document.permalink_pt-br }}"{% if document.permalink.size > 0 or document.permalink_es.size > 0 %},{% endif %}{% endif %}
            {% if document.permalink.size > 0 %}"en": "https://www.azion.com/en{{ document.permalink }}"{% if document.permalink_es.size > 0 %},{% endif %}{%- endif -%}
            {% if document.permalink_es.size > 0 %}"es": "https://www.azion.com/es{{ document.permalink_es }}"{% endif %}
        }{% if forloop.last != true %},{% endif %}
        {%- endfor -%}
    ]
}

And the output is:

"pt-br": [
         "https://www.azion.com/pt-br/casos-de-sucesso/unicesumar/",
         "https://www.azion.com/pt-br/casos-de-sucesso/renner/",
         "https://www.azion.com/pt-br/casos-de-sucesso/nzn/",
         "https://www.azion.com/pt-br/casos-de-sucesso/lendico/",
         "https://www.azion.com/pt-br/casos-de-sucesso/getninjas/",
         "https://www.azion.com/pt-br/casos-de-sucesso/agibank/"
     ],
     "en": [
         "https://www.azion.com/en/success-case/omelete/",
         "https://www.azion.com/en/success-case/unicesumar/",
         "https://www.azion.com/en/success-case/renner/",
         "https://www.azion.com/en/success-case/nzn/",
         "https://www.azion.com/en/success-case/lendico/",
         "https://www.azion.com/en/success-case/getninjas/",
         "https://www.azion.com/en/success-case/agibank/"
     ],
     "es": [  
     ],
     "all": [
       {
           "en": "https://www.azion.com/en/success-case/omelete/"
       },
       {
           "pt-br":
    "https://www.azion.com/pt-br/casos-de-sucesso/unicesumar/",
           "en": "https://www.azion.com/en/success-case/unicesumar/"
       },
       {
           "pt-br": "https://www.azion.com/pt-br/casos-de-sucesso/renner/",
           "en": "https://www.azion.com/en/success-case/renner/"
       },
       {
           "pt-br": "https://www.azion.com/pt-br/casos-de-sucesso/nzn/",
           "en": "https://www.azion.com/en/success-case/nzn/"
       },
       {
           "pt-br": "https://www.azion.com/pt-br/casos-de-sucesso/lendico/",
           "en": "https://www.azion.com/en/success-case/lendico/"
       },
       {
        	"pt-br": "https://www.azion.com/pt-br/casos-de-sucesso/getninjas/",
         	"en": "https://www.azion.com/en/success-case/getninjas/"
       },
       {
        	"pt-br": "https://www.azion.com/pt-br/casos-de-sucesso/agibank/",    
    		"en": "https://www.azion.com/en/success-case/agibank/"
       }
     ]
    }

There are 2 more json files from the blog and website (documentation is generated through the website). With these files published we can start using JavaScript Edge Functions to generate the final content,

https://www.azion.com/sitemap.xml

This sitemap.xml is not a file, it is generated without caching every time it is requested, so there is no danger of a new URL being created and not going into the sitemap.

The flow is quite simple:

  • Receive request which identifies that sitemap.xml is being requested;
  • Fetch the json files;
  • Read content;
  • Build content;
  • Deliver content.
async function pullSitemap() {
    // to configure another sitemap
    // just add the new fetch function in the list
    
    return Promise.all([
        fetch('https://www.urldositemapsite.com/sitemap.json', {mode: 'no-cors'}), // site
        fetch('https://www.urldositemapblog.com/sitemap.json', {mode: 'no-cors'}), // blog
        fetch('https://www.urldositemapcases.com/sitemap.json', {mode: 'no-cors'}) // cases
    ]);
}
async function extractSitemap(rlist) {
    if(!rlist) rlist = [];
    
    var list = [];
    for(var i = 0; i < rlist.length; i++) {
        list.push( rlist[i].json() );
    }
    return Promise.all(list);
}
/////////////////////
// REQUEST HANDLER //
/////////////////////
async function handleRequest(request) {
    var response = [];
    
    try {
        var xml = '';
        
        var headerXML = '<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd http://www.w3.org/1999/xhtml http://www.w3.org/2002/08/xhtml/xhtml1-strict.xsd" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">\n';
        var contentXML = '';
        var footerXML = '</urlset> ';
        
        var pullsitemap = await pullSitemap();
        var extracted = await extractSitemap(pullsitemap);
        
        extracted.forEach(function(item) {
            var all = item.all ? item.all : [];
        
            all.forEach(function(linkdata) {
                var defaulturl = '';
                var ptbr =  linkdata['pt-br'];
                var en = linkdata['en'];
                var es = linkdata['es'];
        
                var loc = '';
                var xhtmlLink = ''
        
                if(ptbr) {
                    loc = '<loc>' + ptbr + '</loc>';
                    defaulturl = ptbr;
                } else if(en) {
                    loc = '<loc>' + en + '</loc>';
                    defaulturl = en;
                } else if(es) {
                    loc = '<loc>' + es + '</loc>';
                    defaulturl = es;
                }
        
                if(ptbr) {
                    xhtmlLink += '\t\t<xhtml:link rel="alternate" hreflang="pt-br" href="' + ptbr + '" />\n';
                }
                if(en) {
                    xhtmlLink += '\t\t<xhtml:link rel="alternate" hreflang="en" href="' + en + '" />\n';
                }
                if(es) {
                    xhtmlLink += '\t\t<xhtml:link rel="alternate" hreflang="es" href="' + es + '" />\n';
                }
        
                xhtmlLink += '\t\t<xhtml:link rel="alternate" hreflang="x-default" href="' + defaulturl + '" />\n';
        
                contentXML += '\t<url>\n\t\t' + loc + '\n' + xhtmlLink +'\t</url>\n';
            });
        });
        
        xml += headerXML;
        xml += contentXML;
        xml += footerXML;
        
        response = new Response(xml.trim());
        response.headers.set("Content-Type", "application/xml");
    } catch(error) {
        response = new Response(`\n${JSON.stringify({error: error })}\n\n`);
        response.headers.set("Content-Type", "application/json");
    }
    
    return response;
}
///////////////////
// REQUEST LISTENER //
/////////////////////
addEventListener('fetch', event => {
    event.respondWith(handleRequest(event.request))
});

That’s it, a little 80-line code builds an automatic sitemap for multiple languages without worrying about regenerating. For each new project, just add in the first lines where the list is executed by a Promise.all([]) .

It’s much simpler when you see it in practice, isn’t it?

Considerations

The fact that we don’t have all those concerns pointed out at the beginning of the post frees us up to be able to spend development time actually developing and delivering valuable features. This reduces the infrastructure cost and changes are made on demand. And we don’t have to worry about security issues, because all of this is already built into the package when using Azion Edge Functions.