Node.js quick start

This quick start is intended to let you quickly try using several common Cloudinary features. It doesn't necessarily employ coding best practices and the code you create here isn't intended for production.

You can perform this quick start in a code sandbox or in a clean project in the dev environment of your choice.

You can also view the completed code of this quick start in a GitHub repo and code explorer.

Tip
If you aren't familiar with Cloudinary, you may want to first take a look at the Developer get started guide for a high-level overview of integrating Cloudinary into your code, and an introduction to the main concepts.

You may also find our Glossary helpful to understand Cloudinary-specific terminology.

Prerequisites

To perform the steps in this quick start, you'll need:

1. Set up and configure the SDK

Install the SDK

In a terminal in your Node.js environment run:

Copy to clipboard
npm install cloudinary

Set your API environment variable

In a terminal, set your CLOUDINARY_URL environment variable.

Replace CLOUDINARY_URL=cloudinary://API_KEY:API_SECRET@CLOUD_NAME with the API environment variable copied from your account credentials:

  • On Mac or Linux:

    Copy to clipboard
    export CLOUDINARY_URL=cloudinary://API_KEY:API_SECRET@CLOUD_NAME
  • On Windows:

    Copy to clipboard
    set CLOUDINARY_URL=cloudinary://API_KEY:API_SECRET@CLOUD_NAME

Important

  • When writing your own applications, follow your organization's policy on storing secrets and don't expose your API secret.
  • If you use a method that involves writing your environment variable to a file (e.g. dotenv), the file should be excluded from your version control system, so as not to expose it publicly.

Configure Cloudinary

Create a new file called index.js and copy and paste the following into this file:

index.js

Copy to clipboard
// Require the cloudinary library
const cloudinary = require('cloudinary').v2;

// Return "https" URLs by setting secure: true
cloudinary.config({
  secure: true
});

// Log the configuration
console.log(cloudinary.config());

2. Upload an image

Copy and paste this into index.js:

index.js (continued)

Copy to clipboard
/////////////////////////
// Uploads an image file
/////////////////////////
const uploadImage = async (imagePath) => {

    // Use the uploaded file's name as the asset's public ID and 
    // allow overwriting the asset with new versions
    const options = {
      use_filename: true,
      unique_filename: false,
      overwrite: true,
    };

    try {
      // Upload the image
      const result = await cloudinary.uploader.upload(imagePath, options);
      console.log(result);
      return result.public_id;
    } catch (error) {
      console.error(error);
    }
};

3. Get and use details of the image

Copy and paste this into index.js:

index.js (continued)

Copy to clipboard
/////////////////////////////////////
// Gets details of an uploaded image
/////////////////////////////////////
const getAssetInfo = async (publicId) => {

    // Return colors in the response
    const options = {
      colors: true,
    };

    try {
        // Get details about the asset
        const result = await cloudinary.api.resource(publicId, options);
        console.log(result);
        return result.colors;
        } catch (error) {
        console.error(error);
    }
};

4. Transform the image

Copy and paste this into index.js:

index.js (continued)

Copy to clipboard
//////////////////////////////////////////////////////////////
// Creates an HTML image tag with a transformation that
// results in a circular thumbnail crop of the image  
// focused on the faces, applying an outline of the  
// first color, and setting a background of the second color.
//////////////////////////////////////////////////////////////
const createImageTag = (publicId, ...colors) => {

    // Set the effect color and background color
    const [effectColor, backgroundColor] = colors;

    // Create an image tag with transformations applied to the src URL
    let imageTag = cloudinary.image(publicId, {
      transformation: [
        { width: 250, height: 250, gravity: 'faces', crop: 'thumb' },
        { radius: 'max' },
        { effect: 'outline:10', color: effectColor },
        { background: backgroundColor },
      ],
    });

    return imageTag;
};

5. Run your code

Copy and paste this into index.js to call the functions you just created:

index.js (continued)

Copy to clipboard
//////////////////
//
// Main function
//
//////////////////
(async () => {

    // Set the image to upload
    const imagePath = 'https://cloudinary-devs.github.io/cld-docs-assets/assets/images/happy_people.jpg';

    // Upload the image
    const publicId = await uploadImage(imagePath);

    // Get the colors in the image
    const colors = await getAssetInfo(publicId);

    // Create an image tag, using two of the colors in a transformation
    const imageTag = await createImageTag(publicId, colors[0][0], colors[1][0]);

    // Log the image tag to the console
    console.log(imageTag);

})();

Save your changes then run the script from the terminal:

Copy to clipboard
node index.js

You can see the image that has been uploaded to your Media Library by copying the secure_url that is returned in the upload response and pasting it in a browser.

Happy people image

You can use the returned image tag to display the image on your website. For now, copy and paste the URL to see the transformed image in the browser:

Transformed image of faces

View the completed code

You can see the whole Node.js script in GitHub, and also in the code explorer below.

Code explorer: Full Node.js example

The full Node.js script is shown in the repl below.

To run it:

  1. In the Console below the code, enter the following to set your API environment variable (replace CLOUDINARY_URL=cloudinary://API_KEY:API_SECRET@CLOUD_NAME with the API environment variable copied from your account credentials):

    Copy to clipboard
    export CLOUDINARY_URL=cloudinary://API_KEY:API_SECRET@CLOUD_NAME
  2. Run the script:

    Copy to clipboard
    node index.js

Important
Do not click the run button, as this clears any environment variables that are set.

This code is also available in GitHub.

Next steps

  • Learn more about the Node.js SDK by visiting the other pages in this SDK guide.
  • Get comprehensive details about Cloudinary features and capabilities:

✔️ Feedback sent!

Rate this page: