Cloudinary Blog

Implement Dynamism in Static Sites With Serverless Functions

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

How to Use the Cloudinary Media Editor Widget

At Cloudinary, we manage the entire pipeline of media assets for thousands of customers of varying sizes from numerous verticals.

As part of our commitment to support the entire flow of media assets, we are now introducing an intuitive media editing widget: an out­-of­-the-­box, interactive UI providing your users with a set of common image editing actions for immediate use on your website or web app. The widget is interactive and simple, built on Cloudinary's transformation capabilities, and requiring only a few lines of code to integrate. Afterwards, you can seamlessly and effortlessly add content to your site or app with no need for in-house image editing capabilities.

Read more
Shoppable Video Is Becoming Popular in E-Commerce

As pandemic restrictions necessitated, many shopping trips in 2020 took place outside the traditional brick-and-mortar store, or at least void of the physical aisle-browsing experience. Same-day curbside pickup became a safe and convenient alternative, and e-commerce transactions skyrocketed as consumers shopped online. In fact, Digital Commerce 360 estimates that, compared to 2019, e-commerce transactions grew by more than 40% last year.

Read more
Enhance Your Travel Site With Cloudinary in Anticipation of a Return to New Normal

Read more
The Benefits of Headless DAMs

Headless is not a buzzword anymore. In fact, the concept of headless architecture is gaining momentum due to the flexibility it offers for composing new experiences and for tackling the undue complexity of an ever-evolving technology stack. That’s because while the evolution of the martech landscape has enabled disruptive, digital innovations, the approach of buying point solutions for solving specific challenges can expose companies to the complicated nature of new technologies, systems, and platforms.

Read more

Building Display Ads With Transparent Video

By Afzaal Ahmad Zeeshan
Build Web Ads With Transparent Video to Attract User Engagement

Billions of views on the Internet every day drive one of the biggest industries on the planet: advertising. The sheer size of that market and the competitive nature of vying for consumer attention results in a constant need for innovation. Readers are jaded, and display ads are blind spots.

Read more