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

On-Demand Viewing of Live Video Presents New Opportunities

In early 2020, Cloudinary was planning its fourth annual ImageCon conference, a two-day event in the heart of San Francisco, where we’d congregate with curious digital-media minds to brainstorm best practices for media management. Instead, the COVID-19 pandemic forced the entirety of ImageCon 2020 online. As with all other events being planned, we had to overhaul the content to be communicated on video. Gratifyingly, we found the right partner—the event platform Bizzabo—to turn that into a reality.

Read more
Why the Future of E-commerce Is Live

In a previous post, I discussed how “going live” is gaining popularity across industries and verticals. What began as a way for gamers to jam together has evolved into a medium for broader entertainment and business purposes. To continue the conversation, this post unpacks the current trends of shoppable live streams to shine a light on how brands are leveraging “lives” to connect with shoppers in new ways.

Read more
An Overview of Live-Streaming Video Trends

“Let’s go live.” For decades, that’s what newscasters say as they cut to real-time footage of a colleague reporting in the field. The live-video feed adds visual interest and perspective to a story beyond what can be communicated by someone sitting behind the news desk. In the same way, live-streaming video nowadays adds context to other consumer environments. From gaming and events to shopping and social media, “going live” enhances everyday experiences, and it’s something anyone can do with relative ease.

Read more
Readying Live Streams for Video on Demand

When planning a live broadcast or stream, companies often overlook the redistribution phase, but live-stream videos are useful well beyond their initial streaming. Why? Because not everyone watches the first run. For a wider audience, it makes sense to repost live content on your website under an “events” tab, on YouTube, and other social sites for video on demand (VOD). However, preparing footage for reposting can be a lot of work.

Read more