Skip to content

Implement Dynamism in Static Sites With Serverless Functions

In this age of most sites being static, a frequently asked question is how much dynamic functionality you can derive from Jamstack. The answer is a lot because you can incorporate reusable APIs in that architecture and leverage serverless, back-end-oriented functions with no back ends in place.

Serverless functions, also called functions as a service, do not mean functions without servers. Rather, they are functions that come into play only when necessary, saving you bandwidth and time. Examples are dynamic data or processes—form submission, authentication, administrator routes, user routes—on sites with static content. In other words, serverless functions enable you to add dynamic capabilities to applications. This article shows you how to do that with simple code examples.

Companies like Amazon, Microsoft, and Netlify make frequent use of serverless functions. Here’s how to build and apply a Netlify function:

1. Create in the root of your application a configuration file called netlify.toml in which to specify where your functions reside, in this case the functions folder. Add this code to netlify.toml:

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

2. Install the Netlify CLI by running npm install netlify-cli.

Most functions are asynchronous. Before initializing one, run the following code to have the function export a handler and incorporate a body:

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

Afterwards, you can execute the above function from your application, which runs on a different port, displaying the content of body at http://localhost:8888/.netlify/functions/function .

Additionally, you can update the Document Object Model (DOM) from the URL by means of query parameters. First, create a source file called you-said.js with this code:

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

You can then set and display a value, e.g., Obinna, for the string parameter text with the URL http://localhost:8888/.netlify/functions/you-said?text=Obinna.

Applying the above concept to page sourcing by means of IDs is a breeze. For a demo, go to the functions folder and create a source file called projects-by-id.js with the code below, which imports 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 defines the variable id as a string parameter and verifies if the input string is, in fact, an ID. If so, the screen response is displayed as JSON at http://localhost:8888/.netlify/functions/project-by-id?id=tt2975590 .

You can also source other data, such as images from third-party services like Cloudinary. Follow the steps below:

1. Create a free Cloudinary account.

2. From your account’s dashboard, grab your Cloudinary name, API key, and API secret and store them as environment variables in a file called .env (see the example below) in your project’s root directory.

CLOUDINARY_NAME=my-project
CLOUDINARY_API_KEY=xxxxxxxxxxxxxxxxxx
CLOUDINARY_API_SECRET=xxxxxxxxxxxxxxxxxxxxx

3. Create a cloudinary-upload.js file in the functions folder with the code below. Be sure to replace the three variables, CLOUDINARY_NAME, CLOUDINARY_API_KEY, and CLOUDINARY_API_SECRET`, with their values for your account.

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)
  };
};

This code connects your application to Cloudinary and sets up the image-upload process. For details on how to upload files to Cloudinary with the serverless function and the useUpload component, see the related documentation.

As evidenced by the above high-level use cases, Jamstack offers significant time and resource savings. Its many flexible capabilities alone make it well worth recommending as the default architecture for building web applications.

Back to top

Featured Post