5. Cloudinary

Cloudinary is a cloud-based service that allows developers to upload, store, manage, and deliver images, videos, and other media files.
It supports automatic file optimization and transformations, making it popular for media management in web and mobile apps.

1. Setting up Cloudinary

  1. Sign up on Cloudinary:
    Go to Cloudinary's website and create a free account.

  2. Get API Credentials:
    After signing up, go to the Dashboard to get your API key, API secret, and cloud name. These are necessary for using Cloudinary's API.

2. Integrating Cloudinary

1. Installing Cloudinary

Install Cloudinary SDK

npm install cloudinary

2. Configuring in .env file

All these we can get from cloudinary dashboard API key

.env

CLOUD_NAME = dj6ykxnzy
CLOUD_API_KEY = 614523246146886
CLOUD_API_SECRET = F9gqoWs9-mw_GsBn7sF-68SKTtk

3. Import and Configure Cloudinary

src/utils/cloudinary.js

import cloudinary from 'cloudinary';

cloudinary.config({
    cloud_name: process.env.CLOUD_NAME,
    api_key: process.env.CLOUD_API_KEY,
    api_secret: process.env.CLOUD_API_SECRET
});

File Upload in Cloudinary

src/utils/cloudinary.js

const uploadOnCloudinary = async (localFilePath) => {
    try { //file path as input and checks if it's valid
        if (!localFilePath) return null
        const response = await cloudinary.uploader.upload(localFilePath, {
            resource_type: "auto" //auto detects file type
        });
        console.log("file is been uploaded", response.url)
        return response
    }
    catch(error){ //If the upload fails, it deletes the local file and returns null.
        fs.unlinkSync(localFilePath)
        return null;
    }
}

export uploadOnCloudinary;

Benefits of Cloudinary