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

Our $2B Valuation

By
Blackstone Growth Invests in Cloudinary

When we started our journey in 2012, we were looking to improve our lives as developers by making it easier for us to handle the arduous tasks of handling images and videos in our code. That initial line of developer code has evolved into a full suite of media experience solutions driven by a mission that gradually revealed itself over the course of the past 10 years: help companies unleash the full potential of their media to create the most engaging visual experiences.

Read more
Direct-to-Consumer E-Commerce Requires Compelling Visual Experiences

When brands like you adopt a direct–to-consumer (DTC) e-commerce approach with no involvement of retailers or marketplaces, you gain direct and timely insight into evolving shopping behaviors. Accordingly, you can accommodate shoppers’ preferences by continually adjusting your product offering and interspersing the shopping journey with moments of excitement and intrigue. Opportunities abound for you to cultivate engaging customer relationships.

Read more
Automatically Translating Videos for an International Audience

No matter your business focus—public service, B2B integration, recruitment—multimedia, in particular video, is remarkably effective in communicating with the audience. Before, making video accessible to diverse viewers involved tasks galore, such as eliciting the service of production studios to manually dub, transcribe, and add subtitles. Those operations were costly and slow, especially for globally destined content.

Read more
Cloudinary Helps Minted Manage Its Image-Generation Pipeline at Scale

Shoppers return time and again to Minted’s global online community of independent artists and designers because they know they can count on unique, statement-making products of the highest quality there. Concurrently, the visual imagery on Minted.com must do justice to the designs into which the creators have poured their hearts and souls. For Minted’s VP of Engineering David Lien, “Because we are a premium brand, we need to ensure that every single one of our product images matches the selected configuration exactly. For example, if you pick an 18x24 art print on blue canvas, we will show that exact combination on the hero images in the PDF.”

Read more
Highlights on ImageCon 2021 and a Preview of ImageCon 2022

New year, same trend! Visual media will continue to play a monumental role in driving online conversions. To keep up with visual-experience trends and best practices, Cloudinary holds an annual conference called ImageCon, a one-of-a-kind event that helps attendees create the most engaging visual experiences possible.

Read more