All Articles

Serverless gives “static” sites super powers

In this age of everything static and very few things “dynamic” the question of just how much functionality can be gotten from the Jamstack is always a question. Luckily the Jamstack promises the ability to incorporate Reusable APIs to give the power of Serverless back-end functions without actually having a backend in place.

Also known as functions as a service, the serverless functions have also played a huge role in how we can add dynamic functionality to our applications. In this article we will look at some applications of serverless functions.

What is a serverless function ?

First of all Serverless functions doesn’t mean functions without servers, it’s a huge misnomer (so are so many other things in tech, but hey who is counting). Instead of giving you a generic definition I will give you a use case that explains Serverless.

Now if you are reading this I assume you know about static sites (another misnomer because it comes off as just having static content, but hey who is counting), these sites can also have some dynamic data or process that they can handle such as, form submission, authentication, admin routes, user routes etc.. This is where serverless functions come in. Think of them as functions on your application that fire only when they are needed and saves you money.

Companies like Amazon, Microsoft and Netlify provide these services. for the purpose of this article we will be using Netlify functions.

Serverless functions use cases

Setting up Netlify functions

The first step to make a configuration file in the root of your application called netlify.toml , it specifies where your functions are. In this case the functions are in the function folder is in the root of the application.

  [build]
  command = "npm run build"
  publish = "_site"
  functions = "functions"

The next step is to install the netlify-cli by running npm install netlify-cli , that helps you run your serverless function with ntl dev.

A simple serverless function.

To initialise a serverless function, if it is going to be an async function (mostly the case) it has to export a handler and incorporate a body. Now this function below does do anything fancy but if you go to the browser it displays the content of the body.

exports.handler = async () => {
    return {
        statusCode:200,
        body: 'Hey I am a serverless function',
    };
};

What we see here is that the function although running on a different port has and can be fired from the application.

Another example of a serverless functions power is allowing you automatically update the DOM from the url using query parameters; Let’s name this file you-said.js

exports.handler = async (event) => {
    const {text}= event.queryStringParameters; 
    return {
        statusCode : 200,
        body : `you said ${text}`
    }
}

The above code block can be reached and displays what you say by localhost:8888/.netlify/functions/you-said?text=obinna in this you can nothing the ?text=obinna this is how to set the value on the screen.

So you can see how we can use what a string parameter’s value is to determine what shows on the screen.

Sourcing pages by ID’s

With the above proof of concept you can apply the concept to sourcing pages by ID’s. let’s create a file in the functions folder and name it projects-by-id.js . In the file we will import a list of projects in JSON.

const projects = require('../data/projects.json');
exports.handler = async ({queryStringParameters}) => {
    const {id} = queryStringParameters;
    const project = projects.find((m) => m.id === id);
    if(!project){
        return{
            statusCode:404,
            body:'Not Found',
        };
    }
    return{
        statusCode:200,
        body: JSON.stringify(project),
    }
}

The above code example sets an id as a string parameter and checks to see that the id provided in in fact an ID, for the sake of this demo I will just display the response on the screen as JSON. The display can be seen at localhost:8888/.netlify/functions/project-by-id?id=tt2975590.

Using serverless to source images from Cloudinary.

We can also use serverless functions to source data or in this case images from 3rd party services. The first step is to create you free Cloudinary account if you don’t already have one. You will need to grab your cloud name, API key and API secret. Theses are best stored as env variables so create a .env file at the projects root and add them.

CLOUDINARY_NAME=my-project
CLOUDINARY_API_KEY=xxxxxxxxxxxxxxxxxx
CLOUDINARY_API_SECRET=xxxxxxxxxxxxxxxxxxxxx

Then in your functions directory create a cloudinary-upload.js, in that file you can add the code block below;

const cloudinary = require("cloudinary").v2;
const dotenv = require("dotenv");
dotenv.config();

cloudinary.config({
  cloud_name: process.env.CLOUDINARY_NAME,
  api_key: process.env.CLOUDINARY_API_KEY,
  api_secret: process.env.CLOUDINARY_API_SECRET
});

// When doing a signed upload, you'll use a function like this
exports.handler = async event => {
  const { file } = JSON.parse(event.body);
  const res = await cloudinary.uploader.upload(file, { ...JSON.parse(event.body) });
  return {
    statusCode: 200,
    body: JSON.stringify(res)
  };
};

The above code, connects your application to a cloudinary and sets up uploading photos, you can use the use-cloudinary documentation to see how this function can be used in components.

Conclusion

In this article, we have looked at serverless functions and the high level use cases where it can be used, the door to serverless really gets you thinking about how much you can save time and resources when moving to the Jamstack architecture, in this way you can see that without a doubt this will become the default way of building and with the many options available it becomes more flexible.