Cloudinary Blog

Implement Dynamism in Static Sites With Serverless Functions

By Obinna Ekwuno
Serverless Functions Deliver Dynamism to Static Sites

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.

A Use Case and Its Setup Procedure

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:

Copy to clipboard
[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:

Copy to clipboard
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:

Copy to clipboard
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.

Page Sourcing With IDs

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.

Copy to clipboard
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 .

Image Sourcing From Cloudinary

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.

Copy to clipboard
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, andCLOUDINARY_API_SECRET`, with their values for your account.

Copy to clipboard
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.

Numerous Application Scenarios

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.

Recent Blog Posts

Generate Names With faker.js and Convert Them to Graphics With Cloudinary

The year was 1994. South Africa held its first fully representative democratic election, Netscape Navigator became the first commercially successful web browser. Coconuts Japan re-released EA Sports' MLBPA Baseball video game under the perhaps surprising title Fighting Baseball. Unlike MLBPA Baseball, which was licensed by the Major League Baseball (MLB), Fighting Baseball could not infringe on MLB trademarks, reference the National League or American League by name, or adopt actual team or player names.

Read more
Partner news: Cloudinary-Getty Images Integration

Supported by intelligent automation, Cloudinary serves as an effective conduit between media asset management and delivery so you can take maximum advantage of assets, compress workflows, and build and coordinate engaging and inspiring customer experiences. Through Cloudinary’s Digital Asset Management (DAM) solution, which employs the company’s innovative image and video APIs, creative and marketing teams can benefit from them, as well as from many AI-powered and automated capabilities. As a result, you can transform, optimize, and deliver media at scale on an intuitive UI.

Read more