Introduction to Serverless/Edge scripting
Tags: serverless, edge, saas
Published: 2020-08-16 09:18:16

Did you ever wonder how cool it will be if you can run things above your actual code without fiddling on your deployed servers? You might be thinking why would you even need that and there can be many reasons. It can be you want to redirect the app to different URL for mobile, want to add some additional tags in the head, give a response before running the code and many more. Serverless scripting is the way to do it.

## Meaning
> Serverless scripting (a.k.a. Edge Scripting) is a Script ( In any language, commonly JS ) run on serverless computes (Edge) is a way to run a piece a code before the execution of your actual app code to perform various functions including prefetch response, appending body, adding headers, returning response code, redirecting the url and similar things.

![](https://cdn-images-1.medium.com/max/2000/1*OrLWBbYY3WVKnsjfYZMynQ.png)

So Basically running the script without your own server but above it on serverless. It’s packaged under various names from various CDN providers like Stackpath serverless scripting, Cloudflare Workers, Amazon Lambda edge

## Working

Serverless scripts can be inserted in the CDN environment that deploys instantly on servers across the world and starts performing the job. The working can be understood from the following image-

![Source: Cloudflare](https://cdn-images-1.medium.com/max/2000/1*QuWb9jJrEad_V-wvAFXOzw.png)*Source: Cloudflare*

So what is happening here is that whenever there is a request, the CDN/ Edge Servers requests that from the origin server. Then it runs another script on top of this response in which you can perform different actions as you like. This is basically modifying the response from the origin server.

![](https://cdn-images-1.medium.com/max/2000/1*76sSbQOV_TWVxEU4HjDB-w.png)

## Implementation

The first requirement is that you need to route the traffic through a CDN or an edge server. Not all but most CDN these days provide this feature like MaxCDN, Stackpath, Cloudflare, AWS Cloudfront.

You then need to activate script functionality and add the script to the serverless/edge section of the provider here is an example script that adds an AMP link tag which is canonical of the actual URL.

    *// check the incoming request
    addEventListener*("fetch", event => {
        event.respondWith(*fetchAndModify*(event.request));
    });
    
    *//function that runs on the requests
    async function fetchAndModify*(request) {
        *const *response = *await fetch*(request);
    
        *// Check response is html content
        if *(
            !response.headers.get("content-type") ||
            !response.headers.get("content-type").includes("text/html")
        ) {
            *return *response;
        }
    
    
        *// Read response body.
        const *text = *await *response.text();
        *// modify the URL
        const *url = response.url.replace("https://",'https://content.');
    
    
        *// add the tag by performing replace on head .
        const *modified = text.replace("<head>",'<head> <link rel="amphtml" href='+url+'/amp >');
    
        *// Return modified response.
        return new *Response(modified, {
            status: response.status,
            statusText: response.statusText,
            headers: response.headers
        });
    }

### Pros

1. No code modification to the actual code.

1. Runs as server-side script even on CSR project.

1. Scalable and deploys to the world in minutes.

1. Saves time on deploying things to the actual code base

### Cons

1. Requires a CDN/ Edge server above the original server to handle requests.

1. Comes at a cost

1. Can’t do a lot of DOM manipulation

## Conclusion

Serverless scripting is simple and efficient. More and more CDN’s and platforms are adapting and offering them as a service. So next time if you are looking for a solution that could be a script that runs before the actual code, serverless scripting is the way to do it.

![](https://cdn-images-1.medium.com/max/2802/1*D28RkXxYtJZ-MTIvNkxZ7A.png)