> ## Documentation Index
> Fetch the complete documentation index at: https://cloudinary.com/documentation/llms.txt
> Use this file to discover all available pages before exploring further.

# Node.js quick start


[readme-version-support-link]:https://github.com/cloudinary/cloudinary_npm#version-support
This quick start lets you get an end-to-end implementation up and running using the Node.js SDK in 5 minutes or less.

#### Prerequisites **To perform this quick start, you'll need:**

* A Cloudinary account. If you don't have one yet, you can quickly [register for free](https://cloudinary.com/users/register_free).
* Your product environment credentials. You can find your [credentials](product_environment_settings#api_keys) on the [API Keys](https://console.cloudinary.com/app/settings/api-keys) page of the Cloudinary Console Settings. 
  * To use your **API environment variable**, copy the provided format and replace the `<your_api_key>` and `<your_api_secret>` placeholders with the actual values found on the page. Your cloud name will already be correctly included in the format.
* A working Node.js development environment with a [supported version][readme-version-support-link] of Node.js.

> **NOTES**:
>
> * This quick start is designed for quick onboarding.  It doesn't necessarily employ coding best practices and the code you create here isn't intended for production.  

> * If you aren't familiar with Cloudinary, you may want to first take a look at the [Developer Kickstart](dev_kickstart) for a hands-on, step-by-step introduction to Cloudinary features. You may also find our [Glossary](cloudinary_glossary) helpful to understand Cloudinary-specific terminology.
> **TIP**: To start with full example apps, see [Node.js sample projects](node_sample_projects).

## 1. Set up and configure the SDK

### Install the SDK

In a terminal in your Node.js environment, run:

```
npm install cloudinary
```

### Set your API environment variable

In a terminal, set your `CLOUDINARY_URL` environment variable.
Copy the **API environment variable** format from the [API Keys](https://console.cloudinary.com/app/settings/api-keys) page of the Cloudinary Console Settings. Replace `<your_api_key>` and `<your_api_secret>` with your actual values. Your cloud name is already correctly included in the format.
* On Mac or Linux:

    ```
    export CLOUDINARY_URL=cloudinary://API_KEY:API_SECRET@CLOUD_NAME
    ```
* On Windows:

    ```
    set CLOUDINARY_URL=cloudinary://API_KEY:API_SECRET@CLOUD_NAME
    ```

> **INFO**:
>
> * 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

```nodejs
// 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());
```

More info about configuration...

You can set any [configuration parameters](cloudinary_sdks#configuration_parameters) in this way. In this case, you're setting the `secure` parameter to ensure that `https` URLs are generated by the SDK. (In the latest version of the Node.js SDK, `secure` is set to true by default, so you wouldn't need to set it here.)

## 2. Upload an image

Copy and paste this into **index.js**:

index.js (continued)

```nodejs
/////////////////////////
// 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);
    }
};
```

More info about upload...

* You can upload from various sources, including local files, but for this quick start you'll use a remote file available at: 
[https://cloudinary-devs.github.io/cld-docs-assets/assets/images/happy_people.jpg](https://cloudinary-devs.github.io/cld-docs-assets/assets/images/happy_people.jpg). See where `imagePath` is set in [Run your code](#5_run_your_code).
* You've set the optional parameters as follows:
  * `use_filename: true`: Sets the [public ID](cloudinary_glossary#public_id) to the filename of the uploaded file.
  * `unique_filename: false`: Does not apply random characters to the public ID (you don't want it to be unique for this quick start).
  * `overwrite: true`: Overwrites any image with the same public ID on upload. 
  Without these parameters set, the default option of using a random public ID would be applied, and a new asset would be created each time.
* See the `upload` method of the [Upload API](image_upload_api_reference#upload) for more optional parameters.
* Learn more about [uploading assets](upload_images) in general.

## 3. Get and use details of the image

Copy and paste this into **index.js**:

index.js (continued)

```nodejs
/////////////////////////////////////
// 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);
    }
};
```

More info about getting details of an asset...

* The `resource` method of the [Admin API](admin_api#get_details_of_a_single_resource_by_public_id) is used to return specific details about the image.
* In this case you specify that the response includes information about colors detected in the image.
* The Admin API is rate-limited, unlike the Upload API.

## 4. Transform the image

Copy and paste this into **index.js**:

index.js (continued)

```nodejs
//////////////////////////////////////////////////////////////
// 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;
};
```

More info about transformations...

* The `cloudinary.image` method of the Node.js SDK is used to create an HTML image tag, with the `src` URL set to the URL of the uploaded asset, but with transformation parameters applied. 
* To return only the URL, and not the whole tag, replace `cloudinary.image` with `cloudinary.url`.
* When the image is delivered via this URL, you will see a transformed version of the image (the original remains intact).
* The applied transformations in this case are:
  * A resize to 250 x 250 pixels, cropping the images to keep the faces.
  * A maximum rounding of corners, resulting in a circular image.
  * An outline of 10 pixels in the most predominant color.
  * A background of the second most predominant color.
* See the [transformation reference](transformation_reference) for details of all transformations.

## 5. Run your code

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

index.js (continued)

```nodejs
//////////////////
//
// 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: 

```
node index.js
```

Check the configuration...

If you set the `CLOUDINARY_URL` environment variable correctly, the response in the **Console** tab will look something like this:

```
{
  cloud_name: 'demo',
  api_key: '1234',
  api_secret: 'abcd',
  private_cdn: false,
  secure_distribution: null,
  secure: true
}
```

Check the upload response...

The response to the upload call looks something like this:

```
{
  asset_id: '843cc951bfaa0406ab46c4a511be352f',
  public_id: 'happy_people',
  version: 1651585298,
  version_id: '879185fc8d13b0147ec7560fcc59444f',
  signature: '924698dcaffd01bdda087419778678a1e84f702e',
  width: 1920,
  height: 1279,
  format: 'jpg',
  resource_type: 'image',
  created_at: '2022-05-03T13:41:38Z',
  tags: [],
  pages: 1,
  bytes: 305948,
  type: 'upload',
  etag: 'a05e4b2dead1465657e9cfc0ab1de643',
  placeholder: false,
  url: 'http://res.cloudinary.com/demo/image/upload/v1651585298/happy_people.jpg',
  secure_url: 'https://res.cloudinary.com/demo/image/upload/v1651585298/happy_people.jpg',
  access_mode: 'public',
  overwritten: true,
  original_filename: 'happy_people',
  api_key: '1234'
}
```

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

![Happy people image](https://res.cloudinary.com/demo/image/upload/v1651585298/happy_people.jpg "thumb:c_scale,h_266, with_code:false")

Check the resource response...

The response to the resource method looks something like this:

```
{
  asset_id: '843cc951bfaa0406ab46c4a511be352f',
  public_id: 'happy_people',
  format: 'jpg',
  version: 1651585298,
  resource_type: 'image',
  type: 'upload',
  created_at: '2022-05-03T13:41:38Z',
  bytes: 305948,
  width: 1920,
  height: 1279,
  access_mode: 'public',
  url: 'http://res.cloudinary.com/demo/image/upload/v1651585298/happy_people.jpg',
  secure_url: 'https://res.cloudinary.com/demo/image/upload/v1651585298/happy_people.jpg',
  next_cursor: 'be5b96157f04cc1ca17ae170f3120d72b33014b52e696d728eaf0334524d9fe2',
  derived: [],
  colors: [
    [ '#F8F3F0', 27.8 ], [ '#DBE0EA', 12 ],
    [ '#D9DBC0', 11.5 ], [ '#CA9379', 9.9 ],
    [ '#85553F', 9.2 ],  [ '#EAF1F6', 8 ],
    [ '#B6CA75', 4.4 ],  [ '#CCD787', 3.3 ],
    [ '#6F8049', 3.1 ],  [ '#4A2C1E', 1.2 ],
    [ '#404727', 1.1 ],  [ '#8F7C7B', 0.9 ],
    [ '#CDB588', 0.7 ],  [ '#627463', 0.7 ],
    [ '#42200B', 0.6 ],  [ '#E1DDE1', 0.6 ]
  ],
  pages: 1,
  usage: {},
  original_filename: 'happy_people',
  etag: 'a05e4b2dead1465657e9cfc0ab1de643',
  rate_limit_allowed: 10000,
  rate_limit_reset_at: 2022-05-03T14:00:00.000Z,
  rate_limit_remaining: 9719
} 
```

Notice that the response includes the most predominant colors in the image.

Check the image tag...

The generated image tag looks something like this:

```
<img src='https://res.cloudinary.com/demo/image/upload/c_thumb,g_faces,h_250,w_250/r_max/co_rgb:F8F3F0,e_outline:10/b_rgb:DBE0EA/happy_people' />
```

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](https://res.cloudinary.com/demo/image/upload/c_thumb,g_faces,h_250,w_250/r_max/co_rgb:F8F3F0,e_outline:10/b_rgb:DBE0EA/happy_people "with_code:false")

## View the completed code

You can see the whole Node.js script in [GitHub](https://github.com/cloudinary-devs/cld-node-sdk-quick-start), and also in the code explorer below.

### Code explorer: Full Node.js example

Here's the full Node.js script: 

This code is also available in [GitHub](https://github.com/cloudinary-devs/cld-node-sdk-quick-start).

You can run it by opening it on Replit, forking it into your own account, and setting your [API environment variable](product_environment_settings#api_keys) in **Secrets**.

![Replit secret](https://cloudinary-res.cloudinary.com/image/upload/f_auto/q_auto/docs/replit_secret.png "thumb:c_scale,w_400/dpr_2.0, width:400, popup:true")
> **TIP**: Enjoy interactive learning? Check out more [code explorers](code_explorers)!
## 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:
    * [Upload guide](upload_images): Provides details and examples of the upload options.
    * [Image transformations guide](image_transformations): Provides details and examples of the transformations you can apply to image assets.
    * [Video transformations guide](video_manipulation_and_delivery): Provides details and examples of the transformations you can apply to video assets.
    * [Transformation URL API Reference](transformation_reference): Provides details and examples of all available transformation parameters. 
    * [Admin API guide](admin_api): Provides details and examples of the methods available for managing and organizing your media assets.
