> ## 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.

# Media Library Widget API reference


The Media Library widget API reference details all the parameter options that you can use when configuring the Media Library widget.

> **See also:**:
>
> * For in-depth information, see the [Media Library widget](media_library_widget) guide.

> * Check out the [Media Library widget code explorers](media_library_widget#code_sandbox) to see implementation examples in HTML and React.

## Installation

To use the Media Library widget, include Cloudinary's Media Library JavaScript file in your HTML:

```js
<script src="https://media-library.cloudinary.com/global/all.js"></script>
```

The `all.js` file instantiates the `cloudinary` class with access to initialization methods, configuration options, callbacks, and events.

## Configuration

When you call the [openMediaLibrary() or createMediaLibrary()](#methods) method, you pass it a set of configuration options. These options include the required `cloud_name` parameter and the optional `api_key` parameter. Additionally, you can include a variety of optional settings that control the behavior and look and feel of the widget.

You can also optionally adjust the values of the **Media Library behavior** options when re-opening the widget using the [show()](#show) method.

### Configuration syntax

The configuration object is passed as the first parameter when initializing the Media Library widget:

```js
window.mediaLibraryHandler = cloudinary.createMediaLibrary(
  {
    // Required authentication options
    cloud_name: 'my_company',
    
    // Optional authentication
    api_key: '1234567890',
    username: 'john_doe@mycompany.com',
    
    // Optional client-side customization
    button_class: 'myBtn',
    button_caption: 'Select Image or Video',
    
    // Optional Media Library behavior
    multiple: true,
    max_files: 10,
    default_transformations: [[{quality: "auto"}, {fetch_format: "auto"}]]
  },
  {
    insertHandler: function(data) {
      data.assets.forEach(asset => {
        console.log('Selected asset:', asset.public_id);
      });
    }
  }
);
```

### Configuration options
{table:class=semiwide-1stcol} Option|Description|Default Value|
|---|---|---|
|**Authentication**|
|`cloud_name`| **Required.** _String._ The cloud_name of the product environment to access.| |
|`api_key`| _String._ The product environment API key. If provided, the API key is validated to ensure it belongs to the specified `cloud_name`.| |
|`username`| _String._ The user name to use when accessing Cloudinary. When this value is provided, if the user is not already logged in, the Cloudinary login screen opens with the specified user name already displayed. When not provided, the user can manually enter any user name and corresponding password in the Cloudinary login screen.  |None|
|`use_saml`| _Boolean._ Whether to perform automatic SSO login via SAML for the specified `username`. This parameter is relevant only if the 'Enforce SAML login' option is disabled for your account. |False |
|`saml_iframe_support`| _Boolean._ Enables opening a new tab for SSO login via SAML, which automatically closes upon completion. Useful for Azure SSO login, as Azure blocks login within an iframe, preventing successful login. **Note:** Browser pop-up blockers may require user permission (once) to allow the new tab. |False |
|**Analytics**| **Note**: Adding analytics is a requirement for becoming a [Cloudinary integration partner](integrations#become_a_cloudinary_integrations_technology_partner).
|`integration`| _Object._  Enables seamless analytics tracking within the widget for analyzing usage patterns and performance metrics. For more information, see [How to add analytics to your integration](integrations_how_to_add_analytics#media_library_widget_integration_configuration).|None
|**Client-side**|
|`button_caption`|_String._ The caption text to display on the button in the page that opens the Media Library.Applied when the `btnPlaceholder` parameter is provided in the widget instantiation method.|`Open Media Library`|
|`button_class` |_String._ The class to use for the button in the page that opens the Media Library. Applied when the `btnPlaceholder` parameter is provided in the widget instantiation method.|None (Uses a default HTML button element.)|
|`inline_container`|_String_ or _HTMLElement_.  The selector string or HTMLElement that will contain the Media Library widget. Include this parameter if you want the Media Library to open as an embedded element in your web page.When opened as modal (default), the Media Library blocks access to your application page. When opened inline, your application is not blocked.| None (opens as a modal dialog box)
|`insert_caption` | _String._ The caption text to display on the Insert button. If you want to use an external mechanism for the insert operation, you can set this option to null or an empty string to hide the built-in insert button entirely.  |`Insert`|  
|`remove_header` | _Boolean_. Whether to remove the blue top banner when opening the widget inline. Only relevant when `inline_container` also has a value set. When opening the widget as a modal dialog box, this parameter is ignored. | False
|`z_index`| _Integer._  Sets the CSS stack order of the Media Library element.Relevant when working with the Media Library widget as a modal dialog (when `inline_container` is not defined).| 99999 (top)
|**Media Library behavior**|  **Note**: These options can also be adjusted using the `show()` method.
|`default_transformations`|_Object[][]._ A transformation object containing one or more  transformations that you want to apply to every inserted media asset. each transformation can include multiple chained components if needed. This is defined in the same way you would define an [eager transformation](eager_and_incoming_transformations#eager_transformations). For example: `[[{quality: "auto"},{fetch_format: "auto"}]]`Your default transformation can also be a complex, chained transformation object that controls the size and quality, adds overlays, and more. Additionally, it can contain more than one transformation definition. In that case, multiple derived images are created for each selected asset and included in the response. **Notes:**If the user selects a transformation from the asset drill-down page, your default transformation is chained after the user's transformation. If your library includes multiple media types (image, video, raw), make sure that your default transformation works well on all relevant types.  |None|
|`max_files`| Max number of media assets that can be added during a single session. Relevant when `multiple=true`.| 20
|`multiple`| _Boolean_. Whether to allow users to select multiple images from the Media Library asset grid. | True
|**Custom show() options** | These options are relevant _only_ for the `show()` method.
|`asset`| _Object._ Instructs the widget to open directly to the Manage page of the Media library with a specified asset. The unique identifier of the asset to open is specified with an `asset` object. The `asset` object can either separately define the `resource_type`, `type`, and `public_id`, or as a single `resource_id` identifier. For example:`{asset: {resource_type: "image", type: "upload", public_id: "sample"}} ` &nbsp;&nbsp;OR  `{asset: {resource_id: "image/upload/sample"}} ` | None
|`collection`| _Object._ Instructs the widget to open in collections view:Passing an empty object opens the collection view showing all collections, for example: `collection: {}`Passing a collection ID opens the widget with a specific collection displayed (the `id` number is the last component of the URL when viewing the collection in the Media Library Console), for example:  `collection: { id: XXXX }` | None
|search| _Object._ Instructs the widget to open in search view:Passing an empty object opens the default search view with no filter, for example: `search: {}`Passing a search expression opens the widget with the view results filtered as per the search expression, for example:  `search: {expression: 'resource_type:image AND tags=kitten'}` See the [Search expressions](search_expressions) documentation for more information | None
|folder| _Object._ Instructs the widget to open in browse mode, displaying the contents of the specified folder, and optionally filtered to a specific asset type. These options are specified with a `folder` object as follows: `{folder: {path: "folder", resource_type: "video"}} ` | Root (Home) folder, All asset types
|`transformation`| _Object._ Instructs the widget to open directly to the Edit page of the Media library with a specified asset, and with a specified transformation already applied. The asset and transformation are specified in URL format with a `transformation` object as follows: `{transformation:{url: "https://res.cloudinary.com/demo/image/upload/c_scale,w_123/a_45/v1653893768/cld-sample-3.jpg"}}` | None

> **NOTE**: All transformations use the JavaScript (legacy) syntax. When looking at transformation examples in the rest of the documentation, you can change the JS tab to display the legacy (cloudinary-core) code examples.

### Callbacks

When instantiating the Media Library widget, you pass a callbacks object containing functions that handle widget events.

#### insertHandler

The `insertHandler` callback function is called when a user selects media assets to insert and closes the Media Library. The widget returns a JSON payload that includes the URL(s) of the selected asset(s), any derived assets based on specified or default transformations, as well as other asset data.

##### Callback signature

```js
function insertHandler(data) {
  // Handle the returned data
}
```

##### Returned data

The returned `data` consists of an array of Objects - one for each inserted asset. Each object includes the following attributes (shown here in alphabetical order):

* `asset_folder`: string ([dynamic folder](folder_modes) mode only)
* `bytes`: number
* `context`: Object[]
* `created_at`: string
* `derived`: Object[]
* `display_name`: string ([dynamic folder](folder_modes) mode only)
* `folder`: string ([fixed folder](folder_modes) mode only)
* `format`: string
* `height`: number
* `public_id`: string
* `resource_type`: string
* `secure_url`: string
* `tags`: string[]
* `type`:"upload"
* `url`: string
* `version`: number
* `width`: number
* [`duration`: number] - for video assets only

> **NOTE**: :title=Note about derived assets

If you configure `default_transformations`, or if the asset already has derived asset versions, the widget includes those transformed assets in the `derived` object of the payload, alongside the original. Each entry has its own `url` and `secure_url`. Cloudinary's best practice is to deliver the derived URLs (`derived.secure_url`) whenever they are available, rather than the original asset.

##### Example

```js
{
  insertHandler: function(data) {
    data.assets.forEach(asset => {
      console.log("Public ID:", asset.public_id);
      console.log("URL:", asset.secure_url);
      if (asset.derived && asset.derived.length > 0) {
        console.log("Derived URL:", asset.derived[0].secure_url);
      }
    });
  }
}
```

---

#### showHandler

Optional callback function that runs when the Media Library widget is displayed.

##### Example

```js
{
  showHandler: function() {
    console.log("Media Library opened");
  }
}
```

---

#### hideHandler

Optional callback function that runs when the Media Library widget is hidden.

##### Example

```js
{
  hideHandler: function() {
    console.log("Media Library closed");
  }
}
```

## Events

After instantiating the Media Library widget, you can register event handlers using the [on()](#on) method to listen for specific widget events.

### upload

The `upload` event is triggered when assets are uploaded through the Media Library widget's embedded upload functionality.

#### Example

```js
window.mediaLibraryHandler.on("upload", (data) => {
  if (data.event === "queues-end") {
    console.log("Upload completed:", data.info.files[0].uploadInfo.public_id);
  }
});
```

> **NOTE**: For a full listing of events triggered by the embedded upload widget, see the [Events](upload_widget_reference#events) section in the Upload Widget API reference.

---

### delete

The `delete` event is triggered when an asset is deleted through the Media Library widget.

#### Example

```js
window.mediaLibraryHandler.on("delete", (data) => {
  console.log("Asset deleted:", data.assets[0].public_id);
});
```

## Methods

The Media Library widget provides both initialization methods for creating widget instances and instance methods for controlling the widget after it's been created.

### Initialization methods

The initialization JavaScript methods are publicly available after including Cloudinary's Media Library JavaScript file.

> **NOTE**: For the list of methods that can be used with the returned widget object from one of these initialization methods, see the [instance methods](#instance_methods) section.

#### createMediaLibrary

Creates a widget object in memory, but does not display it until the [show()](#show) method of the returned widget object is called.

> **TIP**: Improve the perceived performance of your site by creating the widget while your site is loading and then calling the `show()` method from a click event.

##### Syntax

`cloudinary.createMediaLibrary(config, callbacks, btnPlaceholder)`

Parameter | Type | Description
---|---|---
config | Object | A map of the Media Library widget parameters to apply. See the [configuration options](#configuration_options) section for a full list of options available.
callbacks | Object | An object containing callback functions. The primary callback is `insertHandler`, which is called when the user selects media assets. Additional optional callbacks include `showHandler` and `hideHandler`.
btnPlaceholder | String or HTML element | Optional. An HTML element or selector in your web page that will be replaced with a new button that toggles the Media Library instance open and closed. You can configure the appearance and text of this button by defining the `button_class` and `button_caption` configuration options. Alternatively, you can omit this parameter and control when the widget opens by calling the [show()](#show) method programmatically from your own UI elements.

##### Example

```js
window.mediaLibraryHandler = cloudinary.createMediaLibrary(
  {
    cloud_name: 'my_company',
    api_key: '1234567890',
    username: 'john_doe@mycompany.com',
    button_class: 'myBtn',
    button_caption: 'Select Image or Video'
  },
  {
    insertHandler: function(data) {
      data.assets.forEach(asset => {
        console.log('Inserted asset:', JSON.stringify(asset, null, 2));
      });
    }
  },
  document.getElementById('open-btn')
);

// Alternatively, omit the btnPlaceholder parameter and call show() programmatically:
// window.mediaLibraryHandler.show();
```

---

#### openMediaLibrary

Creates a widget object in memory and also opens the widget immediately.

##### Syntax

`cloudinary.openMediaLibrary(config, callbacks, btnPlaceholder)`

Parameter | Type | Description
---|---|---
config | Object | A map of the Media Library widget parameters to apply. See the [configuration options](#configuration_options) section for a full list of options available.
callbacks | Object | An object containing callback functions. The primary callback is `insertHandler`, which is called when the user selects media assets. Additional optional callbacks include `showHandler` and `hideHandler`.
btnPlaceholder | String or HTML element | Optional. An HTML element or selector in your web page that will be replaced with a new button that toggles the Media Library instance open and closed. You can configure the appearance and text of this button by defining the `button_class` and `button_caption` configuration options. Since `openMediaLibrary` opens the widget immediately, this parameter is typically only needed if you want to create a button for reopening the widget later.

##### Example

```js
window.mediaLibraryHandler = cloudinary.openMediaLibrary(
  {
    cloud_name: 'my_company',
    api_key: '1234567890',
    username: 'alice@mycompany.com',
    multiple: true,
    max_files: 8
  },
  {
    insertHandler: function(data) {
      data.assets.forEach(asset => {
        console.log("Inserted asset:", JSON.stringify(asset, null, 2));
      });
    }
  }
);
```

### Instance methods

After the Media Library has been instantiated using one of the [initialization methods](#initialization_methods), you can use the following methods to control and interact with the widget.

#### show

Opens the Media Library widget. If you want to adjust any of the [Media Library behavior](#config_media_library_behavior) or [Custom show() options](#config_custom_show_options) that were defined when you instantiated the widget, you can optionally pass a new `config` object with the settings you want to change for this particular show session.

##### Syntax

`window.mediaLibraryHandler.show(config)`

Parameter | Type | Description
---|---|---
config | Object | Optional. An object containing configuration options to adjust for this show session. You can adjust the Media Library behavior options or specify custom show() options such as opening to a specific folder, asset, or search view.

##### Example

```js
// Open the widget (e.g., from a button click)
document.getElementById('openBtn').addEventListener('click', function() {
  window.mediaLibraryHandler.show();
});

// Open the widget to a specific folder
document.getElementById('openProductsBtn').addEventListener('click', function() {
  window.mediaLibraryHandler.show({
    folder: { path: "products/new-arrivals" }
  });
});

// Open the widget directly to a specific asset
window.mediaLibraryHandler.show({
  asset: { resource_type: "image", type: "upload", public_id: "sample" }
});

// Open with adjusted max_files
window.mediaLibraryHandler.show({
  max_files: 5
});
```

> **NOTE**: When you hide the widget using the [hide()](#hide) method, any adjusted options that were passed in the `show()` command are forgotten, and the settings revert to those set in the initial instantiation.

---

#### hide

Closes the Media Library widget. When you hide the widget, any adjusted options that were passed in the `show()` command are forgotten, and the settings revert to those set in the initial instantiation.

##### Syntax

`window.mediaLibraryHandler.hide()`

##### Example

```js
// Hide the widget
window.mediaLibraryHandler.hide();
```

---

#### on

Registers an event handler for specific widget events. You can use this to listen for `upload` or `delete` events triggered by the Media Library widget.

##### Syntax

`window.mediaLibraryHandler.on(event_name, handler)`

Parameter | Type | Description
---|---|---
event_name | String | The name of the event to listen for. Supported values: `upload`, `delete`
handler | Function | A callback function that will be called when the event is triggered. The function receives event data as a parameter.

##### Example

```js
// Listen for upload events
window.mediaLibraryHandler.on("upload", (data) => {
  if (data.event === "queues-end") {
    console.log("Upload completed:", data.info.files[0].uploadInfo.public_id);
  }
});

// Listen for delete events
window.mediaLibraryHandler.on("delete", (data) => {
  console.log("Asset deleted:", data.assets[0].public_id);
});
```

> **NOTE**: For a full listing of events triggered by the embedded upload widget, see the [Events](upload_widget_reference#events) section in the Upload Widget API reference.

