Back to Blog
Node.js15 min read

Cloudinary Image Upload in Node.js – Complete Guide

Learn Cloudinary image upload integration in Node.js. Complete guide with installation, configuration, image optimization, transformations, and gallery uploads. Step-by-step tutorial.

Cloudinary is the most popular and powerful cloud-based image and video management service for Node.js applications. After building several applications that required image uploads, I realized that storing images on your own server is a terrible idea. You have to worry about storage space, bandwidth costs, image optimization, CDN setup, and scaling issues. That's when I discovered Cloudinary, and it completely changed how I handle images in production applications. Cloudinary makes image management simple and efficient.

Cloudinary is a cloud-based service that handles everything related to images and videos: storage, optimization, transformation, and delivery through a global CDN. Instead of managing image files yourself, you upload them to Cloudinary and get back optimized URLs that you can use anywhere. Cloudinary automatically optimizes images, generates different sizes, and serves them through a fast CDN. Cloudinary image upload is the industry standard for image management in Node.js.

In this complete Cloudinary guide, I'll show you how I integrate Cloudinary with Node.js and Express.js applications. We'll cover setting up the Cloudinary SDK, Cloudinary image upload for single images and galleries, image transformations (resizing, cropping, filters), optimization settings, and deleting images when needed. I'll also share some performance tips I've learned from using Cloudinary in production. This Cloudinary tutorial covers everything you need to know.

Table of Contents: Cloudinary Guide

How to Install Cloudinary: npm Cloudinary Setup

Installing Cloudinary is straightforward. Use npm to install the Cloudinary SDK for Node.js:

npm install cloudinary

Cloudinary Configuration: Cloudinary Config Setup Guide

Setting up Cloudinary config is essential for using Cloudinary in your Node.js application. Here's how to configure Cloudinary:

const cloudinary = require("cloudinary").v2; const fs = require("fs"); const path = require("path"); cloudinary.config({ cloud_name: process.env.CLOUDINARY_CLOUD_NAME, api_key: process.env.CLOUDINARY_API_KEY, api_secret: process.env.CLOUDINARY_API_SECRET, });

Cloudinary Image Upload: Single Image Upload Guide

Cloudinary image upload for a single image is the most common use case. Here's how to create a function to upload a single product image to Cloudinary:

async function uploadProductImageToCloudinary(filename) { try { const file = `./uploads/${filename}`; const uploadedImageResult = await cloudinary.uploader.upload(file); // Generate optimized image URL const optimizedImageUrl = cloudinary.url(uploadedImageResult.public_id, { transformation: [ { quality: "auto", fetch_format: "auto", }, { width: 400, height: 400, crop: "fill", gravity: "auto", }, ], }); const imageData = { optimizedUrl: optimizedImageUrl || "", secureUrl: uploadedImageResult?.secure_url || "", publicId: uploadedImageResult?.public_id || "", url: uploadedImageResult?.url || "", }; // Delete local file after upload try { fs.unlinkSync(path.join(__dirname, "..", "uploads", filename)); } catch (error) { console.log("Error deleting local image", error); } return imageData; } catch (error) { console.log("Error uploading image to Cloudinary", error); return null; } }

Delete Images from Cloudinary: Image Management Guide

Deleting images from Cloudinary is important for managing storage and cleaning up unused images. Here's how to delete images from Cloudinary:

async function deleteImageFromCloudinary(publicId) { try { const deletedImage = await cloudinary.uploader.destroy(publicId, { resource_type: "image", }); console.log("Deleted image from Cloudinary:", deletedImage); return true; } catch (error) { console.log("Error deleting image from Cloudinary", error); return false; } } // Delete multiple images async function deleteMultipleImagesFromCloudinary(publicIds) { if (!publicIds || publicIds.length === 0) { return true; } try { const results = await cloudinary.api.delete_resources(publicIds, { resource_type: "image", }); console.log("Deleted images from Cloudinary:", results); return true; } catch (error) { console.log("Error deleting multiple images from Cloudinary", error); return false; } }

Cloudinary Integration: Using Cloudinary in Product Controller

Integrating Cloudinary image upload in product creation is a common pattern. Here's how to use Cloudinary in your product controller:

const { uploadProductImageToCloudinary, uploadProductGalleryToCloudinary, } = require("../utils/cloudinaryHelper"); async create(req, res) { try { const newProduct = await productModel.create(productData); // Upload main product image to Cloudinary if (req.files.product_image && req.files.product_image.length > 0) { const mainImageData = await uploadProductImageToCloudinary( req.files.product_image[0].filename ); if (mainImageData) { await productModel.update(newProduct.id, { product_image_optimizedUrl: mainImageData.optimizedUrl, product_image_secureUrl: mainImageData.secureUrl, product_image_publicId: mainImageData.publicId, }); } } // Upload gallery images if (req.files.product_gallery && req.files.product_gallery.length > 0) { const galleryFilenames = req.files.product_gallery.map((file) => file.filename); const galleryImages = await uploadProductGalleryToCloudinary(galleryFilenames); if (galleryImages.length > 0) { await productModel.update(newProduct.id, { product_gallery: galleryImages, }); } } const updatedProduct = await productModel.getById(newProduct.id); return res.status(201).json(updatedProduct); } catch (error) { console.error("Error creating product:", error); return res.status(500).json({ message: "Error creating product", error: error.message, }); } }

Environment Variables

CLOUDINARY_CLOUD_NAME=your_cloud_name CLOUDINARY_API_KEY=your_api_key CLOUDINARY_API_SECRET=your_api_secret

Cloudinary Best Practices: Production Tips

Following Cloudinary best practices ensures optimal performance and cost efficiency. Here are the key Cloudinary best practices:

  • Always delete local files after uploading to Cloudinary
  • Use optimized URLs for better performance
  • Store public_id for easy deletion later
  • Implement error handling for upload failures
  • Use transformations for consistent image sizing
  • Clean up old images when updating products

Conclusion: Why Cloudinary is the Best Choice for Image Management

Cloudinary provides a robust solution for image management in Node.js applications. With automatic optimizations, transformations, and CDN delivery, Cloudinary is perfect for product image management in inventory systems. The Cloudinary image upload integration is straightforward and provides excellent performance for image-heavy applications. Cloudinary is the industry standard for cloud-based image management.

Whether you're building a simple image upload feature or a complex system with Cloudinary image upload for galleries, transformations, and optimization, this Cloudinary guide provides the foundation you need. Cloudinary makes image management simple, secure, and efficient. Remember to always use optimized URLs, store public_id for easy deletion, and implement proper error handling for a reliable Cloudinary integration.

For more information, check out the Cloudinary documentation and Cloudinary website for the latest updates and examples. The Cloudinary example code provided in this guide can be adapted to fit your specific use case. Cloudinary is the solution you've been looking for for image management in Node.js.