Upload Images to Cloudinary with Netlify Functions

Ifeoma Imoh

When it comes to creating and delivering your digital assets with the least amount of effort, Cloudinary has you covered with an end-to-end management solution. This article will go through the steps involved in uploading images to Cloudinary using serverless functions.

With serverless functions, we can write backend or server-side code without the burden of managing servers. In this article, we will be using Netlify functions, and it allows us to create, deploy, and manage serverless lambda functions without requiring an AWS account. Still, under the hood, Netlify functions are powered by AWS Lambda.

This article assumes—or hopes is perhaps a better word—that you are familiar with the basics of JavaScript and React.js.

Here is a link to the demo on CodeSandbox and the source code on GitHub.

Prerequisite

To follow this article, I recommend you have the following:

  • Node version 10 or newer.
  • Basic understanding of JavaScript, Serverless Functions, and Node.js.
  • Integrated Development Environment (e.g., Visual studio code).

Project Setup

Open your terminal and run the following command to create a React application in a folder called imageUploader.

1npx create-react-app imageuploader

Now let's install the dependencies we will need for this project.

1npm install netlify cloudinary dotenv

The next step is to install the Netlify CLI tool. Run the following command to install it as a dev dependency.

1npm install -D netlify-cli

Following that, we need to create a folder where our Netlify can find serverless functions. Create a folder called functions at the root of your project. Create a file called uploadImage.js within that folder and add the following code to it. This will be our serverless function.

1exports.handler = async function(event, context) {
2 return {
3 statusCode: 200,
4 body: JSON.stringify({ message: 'Hello World' })
5 }
6 }

We will update the logic for the upload functionalities later, but this is basic enough to show that the API is working for now.

Let's create a netlify.toml file at the root of our project. This is a config file for Netlify, and it will be used to specify how Netlify should build our site. Add the following to the file.

1[build]
2 functions = "functions"

functions is the directory where our serverless function is located.

To access a local development server that supports serverless functions, we need to add a script to the package.json file.

Add the following to the scripts section of your package.json file.

1"dev": "netlify dev"

We're all set up! Run the following command in your terminal to start up your local development server.

1npm run dev

Once the server successfully runs, open the link below in your browser to test the serverless function.

1http://localhost:8888/.netlify/functions/uploadImage

Let's work on the interface we'll use to upload images. Open your App.css file and replace whatever is inside with the following.

1.App {
2 width: 100%;
3 max-width: 450px;
4 min-height: 400px;
5 background-color: #f2f2f2;
6 margin: auto;
7 margin-top: 5rem;
8 display: flex;
9 flex-direction: column;
10 align-items: center;
11 justify-content: center;
12 }
13 h4 {
14 text-align: center;
15 font-size: 1.5rem;
16 font-weight: 600;
17 }
18 .uploadBtn {
19 padding: 1rem 2.5rem;
20 background-color: #370aa0;
21 color: #fff;
22 cursor: pointer;
23 margin-bottom: 1rem;
24 }
25 .imgUrl {
26 width: 100%;
27 height: auto;
28 }

Upload Image Component

Open your App.js file and add the following to it.

1import './App.css';
2 function App() {
3 return (
4 <div className="App">
5 <h4>Upload Images</h4>
6 <input id="upload" type="file" hidden />
7 <label className="uploadBtn" htmlFor="upload">Upload Image</label>
8 </div>
9 );
10 }
11 export default App;

You can test the React app by heading to the following localhost URL:

1http://localhost:8888

The output in the browser should look like this.

Now let's set up our environment variables. Create a root-level file called .env and add the following variable to it.

1CLOUDINARY_NAME="cloud name"
2 CLOUDINARY_API_KEY="api key"
3 CLOUDINARY_API_SECRET="api secret"

Cloudinary Setup

We need to get the values for the variables from Cloudinary. Log in to your Cloudinary account or create a free account if you do not have one already.

After you register and log in to your account, you will be directed to your Dashboard page. The account details section on the dashboard page shows your cloud name, API Key, and API Secret. Copy and add the keys to the environmental variables.

Upload Serverless Function

Now let's update our serverless function. Update your uploadImage.js file with the following.

1const cloudinary = require("cloudinary").v2;
2 const dotenv = require("dotenv");
3 dotenv.config();
4 cloudinary.config({
5 cloud_name: process.env.CLOUDINARY_NAME,
6 api_key: process.env.CLOUDINARY_API_KEY,
7 api_secret: process.env.CLOUDINARY_API_SECRET
8 });
9
10 // When doing a signed upload, you'll use a function like this:
11 exports.handler = async event => {
12 const file = event.body;
13 const res = await cloudinary.uploader.upload(file, {
14 image_metadata: true,
15 });
16 return {
17 statusCode: 200,
18 body: JSON.stringify(res)
19 };
20 };

In the code above, we import Cloudinary and dotenv. We configure Cloudinary and dotenv with the config function.

We're also exporting the handler method, a typical synchronous serverless Lambda function that takes an event as a parameter. We're getting the file from event.body and passing it to Cloudinary's upload method.

In the return statement, we return the 200 status code and body as the response from Cloudinary.

Now let's update the functionality for our frontend so that it works as expected. Update your App.js file with the following.

1import { useState } from 'react';
2 import './App.css';
3 function App() {
4 const [loading, setLoading] = useState(false);
5 const [success, setSuccess] = useState(false);
6 const [imgUrl, setImgUrl] = useState([]);
7
8 const readFile = (file) => {
9 return new Promise((resolve, reject) => {
10 const reader = new FileReader();
11 reader.onload = () => {
12 resolve(reader.result);
13 };
14 reader.onerror = reject;
15 reader.readAsDataURL(file);
16 });
17 };
18 const handleUpload = async (e) => {
19 setSuccess(false);
20 if(e.target.files.length > 0) {
21 setLoading(true);
22 const file = await readFile(e.target.files[0]);
23
24 try {
25 const response = await fetch(
26 "/.netlify/functions/uploadImage",
27 {
28 method: 'POST',
29 body: file,
30 }
31 );
32 const data = await response.json();
33 setLoading(false);
34 setSuccess(true);
35 setImgUrl(data.url);
36 console.log(data.url);
37 }
38 catch (error) {
39 console.error(error);
40 setLoading(false);
41 }
42 }
43 }
44 return (
45 <div className="App">
46 <h4>Upload Images</h4>
47 <input id="upload" type="file" onChange={handleUpload} hidden />
48 <label className="uploadBtn" htmlFor="upload">{loading ? "Uploading..." : "Upload an Image"}</label>
49 {success && <img className="imgUrl" src={imgUrl} alt="Uploaded new" />}
50 </div>
51 );
52 }
53 export default App;

In the code above, we created state for the variables loading, success, and imageURL, which will help us keep track of when an image is uploading when it has already been uploaded and then get the URL for the uploaded image.

In the code above, we created states for the variables loading, success, and imageURL, which will help us keep track of when an image is uploading when it has already been uploaded and then get the URL for the uploaded image.

We have the readFile function, which is used to read a file and convert it to a blob URL in the format Cloudinary accepts.

We also created a function called handleUpload, and as its name suggests, it gets the file that needs to be uploaded and sends the API request to the serverless function we created. It returns a response with the image URL, which we then display after the image has been uploaded successfully.

Head over to your development server and upload an image. Here's what mine looks like after a successful upload. Hopefully, you're up and running as well.

Conclusion

In this article, we learned how to build an image upload feature using Netlify's serverless functions and Cloudinary.

Here are some resources you might find helpful:

Ifeoma Imoh

Software Developer

Ifeoma is a software developer and technical content creator in love with all things JavaScript.