JavaScript SDK v2 (Beta)

Important
The JavaScript SDK v2 is currently in BETA. There may be minor changes to parameter names or other implementation details before the general access release. We invite you to try it out. We would appreciate any feedback via our support team.

Key benefits:

Compared to JavaScript SDK v1, JavaScript SDK v2 provides:

  • A new action-based syntax, designed to make building delivery URLs and transformations more logical and discoverable.
  • A smaller bundle size - you only need to import what you want to use.

Quick start

If you're ready to get coding, jump straight to our Quickstart guide. Otherwise, keep reading to get a more in-depth understanding of the JavaScript SDK v2.

Overview

Cloudinary's JavaScript SDK v2 provides simple, yet comprehensive image and video transformation, optimization, and delivery capabilities that you can implement using code that integrates seamlessly with your existing JavaScript or JS-based framework application.

Related topics
This guide relates to the latest release of the Cloudinary JavaScript SDK v2:

  • For details on all new features and fixes from previous versions, see the js-url-gen CHANGELOG.
  • See the JavaScript migration guide for information on migrating to Cloudinary's JavaScript SDK v2.
  • By default, URLs generated with this SDK include an appended SDK-usage query parameter. Cloudinary tracks aggregated data from this parameter to improve future SDK versions and no individual data is collected. If needed, you can disable the url=>analytics configuration option. Learn more.

Note
The following instructions describe Cloudinary's JavaScript frontend library. For the backend Node.js library, which also covers upload and admin functionality, see the Node.js documentation.

Architecture

The JavaScript SDK v2 can be used independently or together with a frontend framework, such as Angular or React. It contains all the functionality needed to transform, optimize and deliver images and videos from your Cloudinary account. The frontend framework libraries work together with this SDK, leveraging the functionality that it provides, while allowing you to work in your framework of choice.

Two GitHub repositories provide all the functionality:

  • js-url-gen contains all the functionality required to create delivery URLs for your Cloudinary assets based on the configuration and transformation actions that you specify. All the js-url-gen functionality is installed through the @cloudinary/url-gen package.
  • frontend-frameworks contains the framework libraries and plugins that can be used to render images and videos on your site. There are different installation packages for each framework, so for example, React is installed through @cloudinary/react, and Angular is installed through @cloudinary/angular.

Full example

This example shows a transformation URL being created using the @cloudinary/url-gen package. It demonstrates the use of tree shaking to reduce the bundle size, which explains why there are so many import statements.

Copy to clipboard
import {Cloudinary} from "@cloudinary/url-gen";
import {Transformation} from "@cloudinary/url-gen";

// Import required actions.
import {thumbnail, scale} from "@cloudinary/url-gen/actions/resize";
import {byRadius} from "@cloudinary/url-gen/actions/roundCorners";
import {sepia} from "@cloudinary/url-gen/actions/effect";
import {source} from "@cloudinary/url-gen/actions/overlay";
import {opacity,brightness} from "@cloudinary/url-gen/actions/adjust";
import {byAngle} from "@cloudinary/url-gen/actions/rotate";

// Import required qualifiers.
import {image} from "@cloudinary/url-gen/qualifiers/source";
import {Position} from "@cloudinary/url-gen/qualifiers/position";
import {compass} from "@cloudinary/url-gen/qualifiers/gravity";


// Create and configure your Cloudinary instance.
const cld = new Cloudinary({
  cloud: {
    cloudName: 'demo'
  }
}); 

// Instantiate a CloudinaryImage object for the image with public ID, 'front_face'.
const myImage = cld.image('front_face');

// Perform the transformation.
myImage
.resize(thumbnail().width(150).height(150).gravity('face'))  // Crop the image.
.roundCorners(byRadius(20))    // Round the corners.
.effect(sepia())  // Apply a sepia effect.
.overlay(   // Overlay the Cloudinary logo.
  source(
    image('cloudinary_icon_blue')
      .transformation(new Transformation()
      .resize(scale(50)) // Resize the logo.
        .adjust(opacity(60))  // Adjust the opacity of the logo.
      .adjust(brightness(200)))  // Adjust the brightness of the logo.       
  )
  .position(new Position().gravity(compass('south_east')).offsetX(5).offsetY(5))   // Position the logo.
)
.rotate(byAngle(10))  // Rotate the result.
.format('png');   // Deliver as PNG. */

// Render the image in an 'img' element.
const imgElement = document.createElement('img');
imgElement.src = myImage.toURL();

sample transformation

This code creates the URL required to deliver the front_face.jpg image with the following transformations applied:

  • Crop to a 150x150 thumbnail using face-detection gravity to automatically determine the location for the crop
  • Round the corners with a 20 pixel radius
  • Apply a sepia effect
  • Overlay the Cloudinary logo on the southeast corner of the image (with a slight offset). The logo is scaled down to a 50 pixel width, with increased brightness and partial transparency (opacity = 60%)
  • Rotate the resulting image (including the overlay) by 10 degrees
  • Convert and deliver the image in PNG format (the originally uploaded image was a JPG)

And here's the URL that is generated from the above code:

Getting started with JavaScript

If you're using a frontend framework, jump straight to the relevant get started.

If you're using JavaScript without a framework, follow the instructions in the next sections for installation and setup.

Installation

Install the @cloudinary/url-gen package using the NPM package manager:

Copy to clipboard
npm i @cloudinary/url-gen --save

Configuration

You can specify the configuration parameters that are used to create the delivery URLs, either using a Cloudinary instance or per image/video.

Note
Specify the configuration parameters in camelCase, for example cloudName.

Cloudinary instance configuration

If you want to use the same configuration to deliver all your media assets, it's best to set up the configuration through a Cloudinary instance, for example:

Copy to clipboard
// Import the Cloudinary class.
import {Cloudinary} from "@cloudinary/url-gen";

// Create a Cloudinary instance and set your cloud name.
const cld = new Cloudinary({
  cloud: {
    cloudName: 'demo'
  }
});

// cld.image returns a CloudinaryImage with the configuration set.
const myImage = cld.image('sample'); // sample is the public ID of the image.

// This returns: https://res.cloudinary.com/demo/image/upload/sample
const myURL = myImage.toURL();

You can set other configuration parameters related to your cloud and URL as required, for example, if you have your own custom domain name, and want to generate a secure URL (HTTPS):

Copy to clipboard
// Create a Cloudinary instance, setting some Cloud and URL configuration parameters.
const cld = new Cloudinary({
  cloud: {
    cloudName: 'demo'
  },
  url: {
    secureDistribution: 'www.example.com', 
    secure: true 
  }
});

Asset instance configuration

If you need to specify different configurations to deliver your media assets, you can specify the configuration per image/video instance, for example:

Copy to clipboard
// Import the configuration classes.
import URLConfig from "@cloudinary/url-gen/config/URLConfig";
import CloudConfig from "@cloudinary/url-gen/config/CloudConfig";
import {CloudinaryImage} from '@cloudinary/url-gen';

// Set the Cloud configuration and URL configuration
const cloudConfig = new CloudConfig({cloudName: 'demo'});
const urlConfig = new URLConfig({secure: true});

// Instantiate a new image passing the Cloud and URL configurations
const myImage = new CloudinaryImage('sample', cloudConfig, urlConfig);

// This returns: https://res.cloudinary.com/demo/image/upload/sample
const myURL = myImage.toURL();

Plugins

The @cloudinary/html package from frontend-frameworks provides plugins to render the media on your site in the most optimal way and improve your user's experience:

  • Lazy Loading to delay loading images if they are not yet visible on the screen.
  • Responsive images to resize your images automatically based on the viewport size.
  • Image accessibility to make your images more accessible to your users with visual disabilities.
  • Image placeholders to display a lightweight version of an image while the target image is downloading.

Both lazy loading and image placeholders are great techniques for helping to optimize your page load times and, in turn, improve your metrics related to Core Web Vitals.

First, install the @cloudinary/html package:

Copy to clipboard
npm i @cloudinary/html --save

Then, use the required plugins in an HTMLImageLayer, for example, applying the responsive and accessibility plugins:

Copy to clipboard
// Import all the plugins
import {lazyload, responsive, accessibility, placeholder, HtmlImageLayer} from "@cloudinary/html";
import {CloudinaryImage} from "@cloudinary/url-gen";

// Create a new HTML image element and inject it to the page
const imgTag = document.createElement('img');
document.body.appendChild(imgTag);

// Create your image
const myImage = new CloudinaryImage('sample', {cloudName: 'demo'});

// Wire up Cloudinary to work with that element and use the responsive and accessibility plugins
new HtmlImageLayer(imgTag, myImage, [responsive(200), accessibility()]);

Plugin order

We recommend the following order when using our plugins to achieve the best results (omitting any you don't need):

Copy to clipboard
new HtmlImageLayer(imgTag, myImage, [lazyload(), responsive(200), accessibility(), placeholder()]);

Lazy loading

Lazy loading tells the browser not to download images that are not yet visible on the user's screen, and wait until the user scrolls to that image. This feature can potentially save bandwidth for images that are not actually viewed, and decrease the time needed to load a page.

This video shows lazy loading in action. See how the GET request is triggered only when the image is starting to come into the viewport:

To enable the lazy loading feature for a particular image, use the lazyload() plugin. This allows you to specify parameters that control when the image loads. For syntax details, see the reference.

Example: Set root margin and threshold

Load an image when 25% of it is visible. Specify a bounding box around the root element with margins, top: 10px, right: 20px, bottom: 10px, left: 30px:

Copy to clipboard
new HtmlImageLayer(imgTag, myImage, [lazyload('10px 20px 10px 30px', 0.25)]);

Responsive images

You can make your images responsive, so that they automatically resize based on the viewport size. If the viewport is small, then a small image is requested, saving bytes and reducing page load times.

This video shows responsive image behavior in action. See how a new image is requested when the browser is resized, based on the configured step size:

To enable the responsive images feature for a particular image, use the responsive() plugin. You can either specify the step size or a set of image sizes. For syntax details, see the reference.

Example 1: Set step size

Set the step size to 200 pixels:

Copy to clipboard
new HtmlImageLayer(imgTag, myImage, [responsive(200)]);

Example 2: Specify a set of image sizes to use

Specify a set of image sizes (800, 1000 and 1400 pixels):

Copy to clipboard
new HtmlImageLayer(imgTag, myImage, [responsive([800, 1000, 1400])]);

Image accessibility

This feature makes an image more accessible to users by specifying one of the following modes:

Mode Transformation applied
monochrome Reduces the image to use only one color.
darkmode (default) Adds a dark tinting effect to the image.
brightmode Adds a bright tinting effect to the image.
colorblind Adds an effect to differentiate between colors that are similar.
Monochrome image monochrome Dark mode image darkmode Bright mode image brightmode Colorblind assisted image colorblind

To enable the accessibility feature for a particular image, use the accessibility() plugin. For syntax details, see the reference.

Example: Apply an accessibility transformation

Help color blind users by using the colorblind mode:

Copy to clipboard
new HtmlImageLayer(imgTag, myImage, [accessibility('colorblind')]);

Image placeholders

An image placeholder is a lightweight version of a target image that can be downloaded quickly, and will occupy the same location as the intended target image, while the target image is still downloading. Once the target image download has been completed the placeholder is replaced with the final image. This feature is especially useful together with large images.

Placeholder images offer the following features:

  • The page loads quickly without blank locations.
  • No page content 'jumping' as the elements dynamically adjust to add downloaded images.

You can specify four different types of placeholder:

Placeholder type Transformation for the placeholder image
blur (default) A low quality, blurred version of the target image.
pixelate A low quality, pixelated version of the target image.
vectorize A low quality, vectorized version of the target image.
predominant A solid, single color image - the predominant color in the target image.

image placeholders

To add a placeholder for a particular image, use the placeholder() plugin. For syntax details, see the reference.

Example 1: Apply a placeholder transformation

Use a blurred placeholder image while waiting for the full quality image to download:

Copy to clipboard
new HtmlImageLayer(imgTag, myImage, [placeholder('blur')]);

Example 2: Combine lazy loading with a placeholder

You can also combine placeholder images with the lazy loading feature. In this case, when the user scrolls to the image location, the placeholder image is downloaded followed by the target image.

For example, to use a solid, single-color placeholder image and the lazy loading feature:

Copy to clipboard
new HtmlImageLayer(imgTag, myImage, [lazyload(), placeholder('predominant-color')]);

In this video you can see all the different placeholder types combined with lazy loading:

Sample projects

View these sample projects for complete code examples:

✔️ Feedback sent!

Rate this page: