Cloudinary Node SDK

repository·master·Indexed 20 days ago

https://github.com/cloudinary/cloudinary_npm

A programmatic interface for Node.js applications to manage, transform, optimize, and deliver media assets. Version 2.10.0 provides the v2 API entrypoint for administrative operations, asset searching, and uploading via uploader.upload() and uploader.upload_large(). It includes support for custom CacheAdapters, signed authorization tokens, and configuration via environment variables like CLOUDINARY_URL.

Tokens
3.7K
Snippets
13
Records
14
Agent score
71%

What's inside cloudinary

  1. Set up the Photo Album Sample project

    master

    The Photo Album sample is a simple application for uploading images and displaying them in a list. It utilizes the jugglingdb ORM for data management.

    To run this sample:

    1. Configure your Cloudinary credentials by copying the environment variable configuration parameters from your Cloudinary Management Console into a .env file in the project directory, or by exporting the CLOUDINARY_URL variable (e.g., export CLOUDINARY_URL=xxx).
    2. Install dependencies using npm install.
    3. Start the server using npm start. For a development mode server with automatic reloading, use npm run dev.
    4. Access the application in your browser at http://localhost:9000.
    # Configuration
    export CLOUDINARY_URL=cloudinary://api_key:api_secret@cloud_name
    
    # Installation
    npm install
    
    # Run in production mode
    npm start
    
    # OR run in development mode (auto-reload)
    npm run dev
  2. Set up the Basic Sample project

    master

    The Basic sample demonstrates how to upload local and remote images to Cloudinary and generate URLs for applying various image transformations.

    To run this sample:

    1. Configure your Cloudinary credentials by copying the environment variable configuration parameters from your Cloudinary Management Console into a .env file in the project directory, or by exporting the CLOUDINARY_URL variable (e.g., export CLOUDINARY_URL=xxx).
    2. Install dependencies using npm install.
    3. Start the sample using npm run start.
    # Example of exporting the environment variable
    export CLOUDINARY_URL=cloudinary://api_key:api_secret@cloud_name
    
    # Installation and execution
    npm install
    npm run start
  3. Implement a custom CacheAdapter

    master

    To use a custom storage mechanism for Cloudinary caching, you must extend the CacheAdapter class and implement its core methods. The Cache singleton will then use your implementation to store and retrieve values based on asset identifiers and transformations.

    Your adapter must implement the following methods:

    • get(publicId, type, resourceType, transformation, format): Retrieves a value from the cache.
    • set(publicId, type, resourceType, transformation, format, value): Stores a value in the cache.
    • flushAll(): Deletes all values in the cache.

    Note that the Cache singleton automatically handles the generation of the transformation string from your options object before calling these methods.

    const { CacheAdapter } = require('cloudinary').Cache;
    
    class MyCustomAdapter extends CacheAdapter {
      get(publicId, type, resourceType, transformation, format) {
        // Your logic to retrieve from Redis, Memcached, etc.
      }
    
      set(publicId, type, resourceType, transformation, format, value) {
        // Your logic to store in Redis, Memcached, etc.
      }
    
      flushAll() {
        // Your logic to clear the cache
      }
    }
    
    // Register the adapter
    const Cache = require('cloudinary').Cache;
    Cache.setAdapter(new MyCustomAdapter());
  4. Configure Cloudinary using environment variables

    master

    The Cloudinary Node SDK automatically loads configuration from specific environment variables. This is useful for setting up credentials without hardcoding them in your application logic.

    Supported Environment Variables

    • CLOUDINARY_URL: A connection string used to set cloud_name, api_key, api_secret, and other parameters. It must use the cloudinary:// protocol.
      • Format: cloudinary://<api_key>:<api_secret>@<cloud_name>?<query_params>
      • Query Parameters: You can use bracket notation in the query string to set nested configuration keys (e.g., ?foo[bar]=value sets config.foo.bar).
    • CLOUDINARY_ACCOUNT_URL: A connection string for account-level provisioning. It must use the account:// protocol.
      • Format: account://<provisioning_api_key>:<provisioning_api_secret>@<account_id>
    • CLOUDINARY_API_PROXY: Sets the api_proxy configuration key.

    Protocol Requirements

    • CLOUDINARY_URL must start with cloudinary://.
    • CLOUDINARY_ACCOUNT_URL must start with account://.
  5. Transform and optimize assets with `cloudinary.url()`

    master

    Use the cloudinary.url() method to generate URLs for your assets with specific transformations and optimizations applied. Common options include width, height, crop, and fetch_format (e.g., setting fetch_format: 'auto' for automatic format optimization).

    cloudinary.url("sample.jpg", {width: 100, height: 150, crop: "fill", fetch_format: "auto"})
  6. Perform large or chunked uploads with `upload_large()`

    master

    For large files or videos, use cloudinary.v2.uploader.upload_large(). This method supports chunked uploading by specifying a chunk_size in the options object, which helps manage memory and network stability during large transfers.

    cloudinary.v2.uploader.upload_large(LARGE_RAW_FILE, {
      chunk_size: 7000000
    }, (error, result) => {
      console.log(error);
    });
  7. Upload assets with `cloudinary.v2.uploader.upload()`

    master

    Upload images or videos to your Cloudinary account using the uploader.upload() method. You can pass a local file path and an options object, such as an upload_preset to configure the upload behavior.

    cloudinary.v2.uploader.upload("/home/my_image.jpg", {upload_preset: "my_preset"}, (error, result) => {
      console.log(result, error);
    });
  8. Access the Cloudinary v2 API entrypoint

    master

    The lib/v2/index.js file serves as the main entrypoint for the Cloudinary v2 SDK. It aggregates the core Cloudinary functionality (v1) with specialized modules for API management, uploading, and searching.

    To use the v2 features, require the module to access the following sub-modules:

    • api: Administrative API operations.
    • uploader: Asset upload operations (including single and chunked uploads).
    • search: Search operations for assets.
    • search_folders: Search operations specifically for folders.
    const cloudinary = require('cloudinary').v2;
    
    // Access sub-modules
    cloudinary.api....
    cloudinary.uploader....
    cloudinary.search....
    cloudinary.search_folders....
  9. Generate an authorization token

    master

    Use the exported function from lib/auth_token.js to generate a signed Cloudinary authorization token. This token is used to secure assets by restricting access based on IP address, expiration time, Access Control Lists (ACLs), or specific URLs.

    To generate a valid token, you must provide either an acl or a url property in the options object. Additionally, you must provide either an expiration timestamp or a duration (in seconds) to define when the token becomes invalid.

    const generateAuthToken = require('./lib/auth_token');
    
    const token = generateAuthToken({
      key: 'YOUR_SECRET_KEY_HEX',
      acl: 'user_id_123',
      duration: 3600, // Token valid for 1 hour
      ip: '127.0.0.1'
    });
    
    console.log(token); // Outputs something like: __cld_token__=ip=127.0.0.1~exp=1718500000~acl=user_id_123~hmac=abc123def...
  10. Configure the Cloudinary SDK via code

    master

    You can configure the SDK by calling the main Cloudinary module function. The behavior of this function changes based on the arguments provided:

    1. Initialize/Reset: Calling the function with true as the first argument resets the existing configuration.
    2. Set a single value: Pass a key (string) and a value. cloudinary(key, value).
    3. Set multiple values: Pass an object containing configuration keys. cloudinary({ key: value }).
    4. Get a value: Pass a string key to retrieve a specific configuration value. cloudinary(key).
    5. Get full config: Calling the function without arguments returns the entire configuration object.

    Note: If environment variables are present, they are loaded during the first call to the configuration function.

    const cloudinary = require('cloudinary');
    
    // Set multiple configuration options
    cloudinary({
      cloud_name: 'my_cloud_name',
      api_key: '123456789',
      api_secret: 'my_secret'
    });
    
    // Set a single option
    cloudinary('api_proxy', 'http://my-proxy.com');
    
    // Retrieve a specific option
    const apiKey = cloudinary('api_key');
    
    // Retrieve the entire configuration object
    const fullConfig = cloudinary();