Showing a Usage Rights Warning Before Download

Hello Sitecorians! 👋


In this blog, I will show how to warn users in Sitecore Content Hub before they download an asset that has usage conditions. The download starts only after the user clicks Acknowledge and Continue.


I built this for a client, but the need is not specific to one business. Any team that manages licensed or restricted content can ask for it. So if your client asks for something similar, you can follow the same steps and change only the rule.


So, let's get started! 😊


The Use Case

This is a common request from DAM users. Many assets come with conditions on how they can be used: third-party usage rights (talent, photography, fonts, music), an expiry date, an embargo, or markets where the asset may not be used. The download is the moment the asset leaves the DAM, so it is the best moment to remind the user.


Most teams already store these conditions as metadata on the asset: a Restricted flag, a usage rights status, an expiry date or a rights profile. But the Download menu does not show that metadata, so a user can download the asset without ever seeing it.


When a client asks for this, the requirement usually looks like this:

  • When an asset matches a rule (for example, Restricted = Yes), show a warning before any download.
  • The rule, the message and the button text come from configuration, not from code, so each business can set its own.
  • The download starts only after the user acknowledges. Closing the warning cancels it.
  • Assets that do not match the rule download as usual, with no popup.
  • The warning covers every way to download: the Download menu, Custom download, All download options and the version history.


In this blog, I use Content Hub's built-in Restricted field (DRM.Restricted) as the example rule, because every instance has it. You can point the rule at any field you use.



How It Works

The solution is one External React component on the asset details page. It does not replace the Content Hub download. It only holds the click until the user has seen the warning.

The component catches the download click before Content Hub does, and checks the asset against a rule from its configuration (in this blog, Restricted = Yes). If the asset does not match, it lets the click through at once. If it does, it shows the warning, and only Acknowledge and Continue sends the click on to Content Hub.

Choosing the Right Approach


A warning is not the only way to protect an asset. Before you build it, decide how strict the control must be:

Approach

What the user experiences

Use it when

Permissions

Cannot download at all

The asset must never leave the DAM for that user group

Approval before download

Requests the asset and waits

Every use needs a person to check it

Warning before download (this blog)

Sees the conditions, acknowledges, downloads

Users are trusted but must be reminded

Metadata on the page only

Sees nothing unless they look

The conditions are low risk


The warning is the light option: no waiting and no admin work, and users cannot say they were not told. You can also combine the options, for example permissions for external users and the warning for internal users.


Typical rules other businesses use:

  • The asset has third-party rights (talent, music, fonts, photography).
  • The usage rights have expired, or expire soon.
  • The asset is under embargo until a launch date.
  • The asset may be used only in some markets or channels.
  • The asset is for internal use only.


Step 1: Define the Rule

Start with the business decision: which assets need a warning? Pick one field that answers it. It can be a relation (an option list or a taxonomy, like Restricted = Yes) or a property (like a usage rights status).

Put the rule in the component's configuration, so the business can change it without a new build:


{
  "rule": {
    "type": "relation",
    "name": "DRM.Restricted.RestrictedToAsset",
    "warnWhen": ["DRM.Restricted.Yes"]
  },
  "title": "Download confirmation",
  "message": "This asset has third-party usage rights. Check that you are allowed to use it for your needs.",
  "buttonText": "Acknowledge and Continue"
}


For a property, set type to property and list the values that need the warning:

"rule": {
  "type": "property",
  "name": "UsageRightsStatus",
  "warnWhen": ["Restricted", "Expired"]
}


For a relation, use the option's identifier, not its label. Identifiers do not change with the language and are not renamed by mistake. In the example, Restricted = Yes has the identifier DRM.Restricted.Yes.

Tip: If the rule needs more than one field (for example, restricted, or the rights expire within 30 days), calculate one field on the server instead, with a script or an Azure Function, and point the rule at that field. The component stays simple, and every page gets the same answer.


Step 2: Create the External Component Project

The warning is an External React component on the page. Content Hub loads a JavaScript module that exports a function called createExternalRoot. That function gets the component's element and returns render and unmount.

I used plain TypeScript with no framework, because the component only needs a small dialog. Create a folder and install TypeScript:


mkdir usage-rights-warning && cd usage-rights-warning
npm init -y
npm install typescript --save-dev

Add a tsconfig.json:


{
  "compilerOptions": {
    "target": "ES2020",
    "module": "ESNext",
    "lib": ["DOM", "ESNext"],
    "strict": true,
    "outDir": "out"
  },
  "include": ["index.tsx"]
}


The code goes in index.tsx. Here is the skeleton:


const LOG_PREFIX = "UsageRightsDownloadWarning:";

interface WarningRule {
    type: "relation" | "property";
    name: string;        // relation or property name
    warnWhen: string[];  // identifiers (relation) or values (property) that need the warning
}

interface WarningConfig {
    rule: WarningRule;
    title: string;
    message: string;
    buttonText: string;
}

// Used when the page gives no configuration
const DEFAULT_CONFIG: WarningConfig = {
    rule: { type: "relation", name: "DRM.Restricted.RestrictedToAsset", warnWhen: ["DRM.Restricted.Yes"] },
    title: "Download confirmation",
    message: "This asset has usage conditions. Check that you are allowed to use it for your needs.",
    buttonText: "Acknowledge and Continue"
};

interface Context {
    config?: Partial<WarningConfig>;
    options?: { entityId?: number };
}

let config = DEFAULT_CONFIG;
let entityId: number | undefined;
let shouldWarn = false;
let ruleCheck: Promise<void> = Promise.resolve();
let pendingTrigger: HTMLElement | null = null; // the download click we are holding
let allowNextClick = false;                    // lets the replayed click through

export default function createExternalRoot(rootElement: HTMLElement) {
    return {
        render(context: Context) {
            config = { ...DEFAULT_CONFIG, ...(context?.config ?? {}) };
            entityId = context?.options?.entityId;
            rootElement.innerHTML = getHtmlElements();
            rootElement.querySelector("#closebtn")?.addEventListener("click", onClose);
            rootElement.querySelector("#ackbutton")?.addEventListener("click", onAcknowledge);

            document.removeEventListener("click", onDocumentClick, true);
            document.addEventListener("click", onDocumentClick, true);

            refreshRule();
        },
        unmount() {
            document.removeEventListener("click", onDocumentClick, true);
            rootElement.innerHTML = "";
        }
    };
}


On the asset details page, Content Hub passes the asset's ID in context.options.entityId and the component's configuration in context.config. If your version uses other names, log context once in render() and check.


Step 3: Check the Rule

The component reads the rule's field through the REST API. The call runs in the user's own session, so no token is needed. One function handles both rule types:


function refreshRule() {
    ruleCheck = fetchShouldWarn().then(value => {
        shouldWarn = value;
    });
}

async function fetchShouldWarn(): Promise<boolean> {
    if (!entityId) {
        console.error(`${LOG_PREFIX} no entity id - showing the warning`);
        return true;
    }
    try {
        const { type, name, warnWhen } = config.rule;
        const values = type === "relation"
            ? await getRelationIdentifiers(entityId, name)
            : await getPropertyValues(entityId, name);
        return values.some(value => warnWhen.includes(value));
    } catch (err) {
        console.error(`${LOG_PREFIX} rule check failed for ${entityId} - showing the warning`, err);
        return true;
    }
}

// Identifiers of the related options, e.g. ["DRM.Restricted.Yes"]
async function getRelationIdentifiers(id: number, relation: string): Promise<string[]> {
    const data = await getJson(`/api/entities/${id}/relations/${relation}?includeIdentifier=true`);
    const parents = data?.parents ?? (data?.parent ? [data.parent] : []);
    return parents.map((p: { identifier?: string }) => p.identifier ?? "");
}

// Values of a property; multi-language values are flattened
async function getPropertyValues(id: number, property: string): Promise<string[]> {
    const entity = await getJson(`/api/entities/${id}`);
    const value = entity?.properties?.[property];
    const values = value && typeof value === "object" && !Array.isArray(value) ? Object.values(value) : [value];
    return values.flat().filter(v => v != null).map(String);
}

async function getJson(url: string) {
    const response = await fetch(url);
    if (!response.ok) throw new Error(`HTTP ${response.status} for ${url}`);
    return response.json();
}


If the check fails, the function returns true and the warning is shown. It is safer to show the warning once too often than to skip it on a restricted asset.


The check runs when the page loads, so it is usually done before the user clicks Download. If someone changes the rule's field on the open page, run the check again:


const REFRESH_EVENTS = ["ENTITY_SAVED", "ENTITY_UPDATED", "ENTITY_REFRESHED"];

const onEntityChanged = (evt: Event) => {
    const id = (evt as CustomEvent<{ id?: number }>).detail?.id;
    if (entityId && Number(id) === Number(entityId)) refreshRule();
};

// in render():   REFRESH_EVENTS.forEach(name => window.addEventListener(name, onEntityChanged));
// in unmount():  REFRESH_EVENTS.forEach(name => window.removeEventListener(name, onEntityChanged));


Step 4: Catch Every Download Click

This is the main part. Content Hub builds the Download menu only when the user clicks the Download button. So a click handler attached to the menu items in render() never finds them.


The fix is one click listener on the whole document, in the capture phase. The capture phase runs before Content Hub's own handler, so the component can stop the click before the download starts.


First, list everything that starts a download:

const DOWNLOAD_TRIGGER_SELECTOR = [
    'a[data-testid="download"]',               // a rendition in the Download menu
    'a[data-testid="downloadRendition"]',      // version history / original file
    'span[data-testid="custom-download"]',     // "Custom download"
    'span[data-testid="all-download-options"]' // "All download options"
].join(", ");


Then hold the click, wait for the check, and either show the warning or let the click through:


function onDocumentClick(event: MouseEvent) {
    const target = event.target instanceof Element ? event.target : null;
    const trigger = target?.closest<HTMLElement>(DOWNLOAD_TRIGGER_SELECTOR);
    if (!trigger) return;

    // The click we replay after "Acknowledge": let Content Hub download
    if (allowNextClick) {
        allowNextClick = false;
        return;
    }

    // Hold the click
    event.preventDefault();
    event.stopImmediatePropagation();
    pendingTrigger = trigger;

    ruleCheck.then(() => {
        if (pendingTrigger !== trigger) return;
        if (shouldWarn) {
            hideMenu(trigger);
            setVisible("#URDownloadWarning", true);
        } else {
            replay(trigger);
        }
    });
}

function replay(trigger: HTMLElement) {
    if (!trigger.isConnected) {
        console.error(`${LOG_PREFIX} download option is no longer on the page - please click it again`);
        return;
    }
    allowNextClick = true;
    trigger.click();
}


The trick is replay(). The component does not download the file itself. It sets allowNextClick and clicks the same menu item again. This time the listener lets the click through, and Content Hub downloads the file as usual, with the right rendition, its own permissions and its own download tracking.

Note: The data-testid values come from the Content Hub UI. They can change after an upgrade, so check them in the browser dev tools if the warning stops showing.


Step 5: Handle Acknowledge and Close

While the click is held, Content Hub's Download menu stays open and sits on top of the dialog. So the component hides the menu while the warning is open:


const MENU_SELECTOR = '[id^="operation-dropdown-menu"]';
let hiddenMenu: HTMLElement | null = null;

function hideMenu(trigger: HTMLElement) {
    hiddenMenu = trigger.closest<HTMLElement>(MENU_SELECTOR);
    if (hiddenMenu) hiddenMenu.style.visibility = "hidden";
}

function restoreMenu() {
    if (hiddenMenu) hiddenMenu.style.visibility = "";
    hiddenMenu = null;
}

function closeMenu(menu: HTMLElement | null) {
    if (!menu?.isConnected) return;
    const list = menu.querySelector<HTMLElement>('[role="menu"]') ?? menu;
    list.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
    if (menu.isConnected) menu.querySelector<HTMLElement>(".MuiBackdrop-root, .MuiModal-backdrop")?.click();
}


I change only visibility. Do not overwrite the menu's inline style: the menu uses it to position itself and to open and close, and overwriting it leaves an invisible menu over the page.

Now the two buttons:


function onAcknowledge() {
    setVisible("#URDownloadWarning", false);
    const trigger = pendingTrigger;
    pendingTrigger = null;
    restoreMenu();
    if (trigger) replay(trigger); // Content Hub downloads and closes its menu
}

function onClose() {
    setVisible("#URDownloadWarning", false);
    pendingTrigger = null;
    const menu = hiddenMenu;
    restoreMenu();
    closeMenu(menu); // cancel: no download
}

function setVisible(selector: string, visible: boolean) {
    const el = document.querySelector<HTMLElement>(selector);
    if (el) el.style.display = visible ? "block" : "none";
    else console.error(`${LOG_PREFIX} could not find element: ${selector}`);
}


Step 6: Add the Warning Dialog

The dialog is plain HTML with scoped CSS. Every rule starts with #URDownloadWarning, so the styles do not leak into the rest of Content Hub:


function getHtmlElements() {
    return `
<style>
    #URDownloadWarning {
        position: fixed; z-index: 2100; inset: 0; padding: 24px;
        background: rgba(0, 0, 0, .5);
    }
    #URDownloadWarning .dialog {
        width: min(560px, 100%); margin: 15vh auto 0; border-radius: 8px;
        background: #fff; box-shadow: 0 10px 30px rgba(0, 0, 0, .24);
        font-family: Inter, sans-serif; font-size: 14px;
    }
    #URDownloadWarning header { display: flex; justify-content: space-between; align-items: center; padding: 16px 24px; }
    #URDownloadWarning h2 { margin: 0; font-size: 18px; text-transform: uppercase; }
    #URDownloadWarning p { margin: 0; padding: 8px 24px 24px; line-height: 22px; }
    #URDownloadWarning footer { display: flex; justify-content: flex-end; padding: 8px 16px 16px; }
    #URDownloadWarning #ackbutton {
        height: 38px; padding: 0 16px; border: 0; border-radius: 6px; cursor: pointer;
        color: #fff; background: var(--primary-500, #7802e9); font-weight: 600;
    }
</style>

<div id="URDownloadWarning" role="presentation" style="display: none;">
  <section class="dialog" role="dialog" aria-modal="true" aria-labelledby="ur-title">
    <header>
      <h2 id="ur-title">${escapeHtml(config.title)}</h2>
      <button id="closebtn" type="button" aria-label="Close">✕</button>
    </header>
    <p>${escapeHtml(config.message)}</p>
    <footer>
      <button id="ackbutton" type="button">${escapeHtml(config.buttonText)}</button>
    </footer>
  </section>
</div>`;
}

function escapeHtml(text: string) {
    const div = document.createElement("div");
    div.textContent = text;
    return div.innerHTML;
}


The title, message and button text come from the configuration, so the business (or the legal team) can change the wording without a new build. escapeHtml keeps that text safe to put into the page.


Step 7: Build and Upload the Component

Build the code:

npx tsc


This writes out/index.js. Then add it to Content Hub:

  1. Upload out/index.js as an asset (or a portal file), and copy its public link.
  2. Go to Manage → Pages and open the Asset details page.
  3. Add a new External React component to the page. Any zone works, because the dialog covers the whole screen.
  4. In the component's settings, set the code link to your uploaded index.js.
  5. In the component's Configuration, paste your rule JSON from Step 1.
  6. Save the page.

To use a different rule later, change only the configuration. The code stays the same.


Step 8: The Search Page (Optional)

Users can also download from the search results, from the asset card's Download menu and from Quick View. The same component works there with two changes.


  1. Find the asset from the card. The search page has no entityId in the context. Instead, find the clicked card, read its identifier from the search-grid-item-<identifier> attribute, and get the asset ID with /api/entities/identifier/<identifier>. Start this check when the user clicks the card's Download button, before they pick a rendition.
  2. Add the dialog to <body>. Inside the component's own element, the dialog sits under Quick View. Create a div, append it to document.body, and remove it in unmount().

Then add the component to the Search page the same way as in Step 7.


It's Working! 🎉

Open a restricted asset and click Download, then pick any rendition. The warning appears and the download waits.


Asset

Action

Result

Restricted = Yes

Pick a rendition

Warning shown, download held

Restricted = Yes

Acknowledge and Continue

The rendition downloads

Restricted = Yes

Close (✕)

No download, the menu closes

Restricted = Yes

Custom download / All download options

Warning shown first

Restricted = No

Pick a rendition

Downloads at once, no warning


If something does not work, open the browser console and filter on UsageRightsDownloadWarning. Every error from the component starts with that prefix.


Conclusion

With one external component and a rule in its configuration, users see an asset's usage conditions before they download it. The rule can point at any field your business already uses: a Restricted flag, a usage rights status, an expiry or an embargo. The component holds the click, checks the rule and replays the click after the user acknowledges. Content Hub still does the download itself, so renditions, permissions and download tracking work as before.


I hope this helps you in your Content Hub journey! If you have any questions, feel free to drop a comment below. 😊


Stay tuned for more! 👋

Post a Comment (0)
Previous Post Next Post