@dotcms/experiments

中文文档
26.11.17-1发布于 2026/11/17MITTypeScriptES Module近 30 天下载 5049

Official JavaScript library to use Experiments with DotCMS.

原始使用文档
文档目录20 节
  1. Overview
  2. When to Use It
  3. Key Features
  4. Table of Contents
  5. Installation
  6. Which SDK Version Should I Use?
  7. Getting Started
  8. Public API
  9. withExperiments Higher-Order Component
  10. Configuration Object
  11. Usage
  12. With @dotcms/react (Recommended)
  13. Next.js App Router
  14. Configuration Best Practices
  15. Anti-patterns
  16. How It Works
  17. Troubleshooting
  18. Support
  19. Contributing
  20. Licensing

dotCMS Experiments SDK

The @dotcms/experiments SDK is the official dotCMS JavaScript library that helps add A/B testing to your web applications. It handles user assignments to different variants of a page and tracks their interactions.

Overview

When to Use It

  • Adding A/B testing capabilities to your web application
  • Running experiments to optimize user experience
  • Testing different page variants with real users
  • Tracking experiment performance with DotCMS Analytics

Key Features

  • User Assignment to Experiments: Automatically assigns users to different experimental variants, ensuring diverse user experiences and reliable test data
  • Link Verification for Redirection: Checks links to ensure users are redirected to their assigned experiment variant, maintaining the integrity of the testing process
  • Automatic PageView Event Sending: Automatically sends PageView events to DotCMS Analytics, enabling real-time tracking of user engagement and experiment effectiveness

Table of Contents

Installation

Install the package via npm:

npm install @dotcms/experiments

Or using Yarn:

yarn add @dotcms/experiments

Which SDK Version Should I Use?

dotCMS SDKs are published in lockstep with dotCMS itself: every @dotcms/* package ships at the exact same version number as the dotCMS release it was built for (e.g. dotCMS 26.7.14-1 → @dotcms/[email protected], @dotcms/[email protected], and so on).

Simple rule of thumb: use the SDK version that matches your dotCMS instance's version.

You don't have to upgrade the SDK every time dotCMS releases a new version (or vice versa). Most releases don't change anything the SDKs rely on, so an older SDK usually keeps working fine against a newer dotCMS instance. Occasionally, though, a release does include a real breaking change — and if your SDK is older than that point, it will stop working correctly.

You don't need to track this yourself: your dotCMS instance always knows the oldest SDK version it still supports, and the SDK checks itself against it automatically. If you're using an SDK that's too old, you'll see a clear warning in your console telling you to upgrade.

Recommendation: pin your SDKs to the same version as your dotCMS instance, and only bump them when you upgrade dotCMS — or when the console tells you to.

On an LTS release? LTS releases don't currently get their own matching SDK version. Until that's addressed, use the SDK version published for the closest regular release at or before your LTS version.

Want more background on how dotCMS releases and support windows work? See Release & Support Lifecycle.

Getting Started

Public API

The package exports one public symbol:

ExportDescription
withExperimentsHOC that wraps a layout component (typically DotCMSLayoutBody) with experiment handling

DotExperimentsProvider and other internals are not part of the public API. Do not import them — withExperiments wires the provider internally.

withExperiments Higher-Order Component

withExperiments wraps your page component with experiment functionality:

  • User assignment to experiment variants
  • Automatic redirection to the correct variant
  • Prevention of content flickering during variant loading
  • Automatic page view tracking to dotCMS Analytics
  • Click event handling to maintain variant consistency across navigation

Important: withExperiments uses React hooks internally. It must be called unconditionally on every render of the component that uses it. See Anti-patterns.

Configuration Object

The config object passed to withExperiments accepts the following properties:

PropertyRequiredDefaultDescription
apiKeyYes—jsKey from the dotCMS Analytics / Experiments app (frontend key, not m2m)
serverYes—dotCMS origin URL (e.g. https://your-dotcms-instance.com) — not a CDN
redirectFnNowindow.location.replaceSPA redirect function (e.g. router.replace in Next.js)
trackPageViewNotrueEnable/disable automatic page view tracking
debugNofalseVerbose logging in the browser console

Usage

Use separate views or routes for pages with and without experiments. This avoids calling withExperiments conditionally in the same component.

// views/StandardPage.tsx — no experiments
"use client";

import { DotCMSLayoutBody, useEditableDotCMSPage } from "@dotcms/react";

import { pageComponents } from "@/components/content-types";

export function StandardPage({ pageContent }) {
    const { pageAsset } = useEditableDotCMSPage(pageContent);

    return (
        <main>
            <DotCMSLayoutBody page={pageAsset} components={pageComponents} />
        </main>
    );
}
// views/ExperimentsPage.tsx — experiments always enabled on this view
"use client";

import { withExperiments } from "@dotcms/experiments";
import { DotCMSLayoutBody, useEditableDotCMSPage } from "@dotcms/react";
import { useRouter } from "next/navigation";

import { pageComponents } from "@/components/content-types";

export function ExperimentsPage({ pageContent }) {
    const { pageAsset } = useEditableDotCMSPage(pageContent);
    const { replace } = useRouter();

    const LayoutBody = withExperiments(DotCMSLayoutBody, {
        apiKey: process.env.NEXT_PUBLIC_DOTCMS_ANALYTICS_KEY!,
        server: process.env.NEXT_PUBLIC_DOTCMS_HOST!,
        redirectFn: replace,
        debug: process.env.NEXT_PUBLIC_DOTCMS_DEBUG === "true",
    });

    return (
        <main>
            <LayoutBody page={pageAsset} components={pageComponents} />
        </main>
    );
}

Wire each view to its own route in the App Router (for example /blog for experiments, catch-all for standard pages).

Learn more about DotCMSLayoutBody: See the @dotcms/react SDK documentation.

Next.js App Router

Canonical working example: examples/nextjs-analytics-experiments

That project demonstrates:

  • Analytics on all routes via @dotcms/analytics in layout.tsx
  • Experiments isolated to /blog via withExperiments in a dedicated view
  • Safe separation that avoids rules-of-hooks violations in UVE

Environment variables (see the example's .env.local.example):

NEXT_PUBLIC_DOTCMS_HOST=http://localhost:8080      # dotCMS origin — NOT a CDN
NEXT_PUBLIC_DOTCMS_ANALYTICS_KEY=                  # jsKey (frontend key)
NEXT_PUBLIC_DOTCMS_DEBUG=true

Verification (DevTools → Network):

  1. On experiment routes: POST {HOST}/api/v1/experiments/isUserIncluded
  2. With debug: true: [dotCMS ...] logs in the console
  3. Open the page in UVE — no "client-side exception" overlay

Configuration Best Practices

  • Use environment variables for apiKey and server
  • Dedicated routes/views for experiment pages — do not toggle withExperiments with a ternary on apiKey in the same component
  • Framework router: pass router.replace (Next.js) or equivalent to redirectFn for SPA navigation
  • Origin URL: server must point to the dotCMS instance origin. Do not use Azure Front Door, CloudFront, or other CDNs — experiment API responses are session-specific and must not be cached at the edge
  • Aligned SDK versions: keep @dotcms/client, @dotcms/react, @dotcms/uve, @dotcms/types, and @dotcms/experiments on the same version line
  • Debug mode: enable during development to troubleshoot assignment issues

Anti-patterns

Do not use these patterns — they can crash Next.js App Router pages and the UVE editor:

// ❌ Conditional withExperiments — violates rules of hooks
const Layout = experimentConfig.apiKey
    ? withExperiments(DotCMSLayoutBody, config)
    : DotCMSLayoutBody;

// ❌ Early return before withExperiments in the same component
if (!apiKey) return <DotCMSLayoutBody {...props} />;
const Layout = withExperiments(DotCMSLayoutBody, config);

// ❌ Importing internal provider
import { DotExperimentsProvider } from "@dotcms/experiments";

// ❌ CDN as server
server: "https://cdn.example.com"

Use separate components/routes instead (see With @dotcms/react).

How It Works

Once you wrap your component with withExperiments, the SDK automatically handles:

  1. User Assignment: Assigns users to experiment variants when they visit a page with an active experiment
  2. Automatic Redirection: Redirects users to their assigned variant URL (prevents seeing the wrong variant)
  3. Flicker Prevention: Hides content during redirection to avoid showing the wrong variant momentarily
  4. Navigation Handling: Maintains variant consistency when users click links
  5. Analytics Tracking: Sends pageview events to DotCMS Analytics automatically

Learn More: DotCMS A/B Testing Experiments

Troubleshooting

SymptomLikely causeWhat to do
UVE crash: "A client-side exception has occurred"withExperiments called conditionally, or experiments initializing before UVE state is readyUse a dedicated experiments view; never use apiKey ? withExperiments(...) : DotCMSLayoutBody
GET /api/v1/experiments/DEFAULT 404Known backoffice issue — variant name "DEFAULT" passed as experiment IDHarmless in headless apps; backoffice fix tracked separately
"No experiments assigned to the client"Experiment not in Running status, or no analytics session yetConfirm experiment status in dotCMS; verify apiKey and server
No isUserIncluded requestMissing apiKey, wrong route, or experiments view not mountedCheck env vars; confirm the page uses the experiments view
Events go to wrong hostserver points to CDN instead of dotCMS originSet server to the dotCMS instance URL

Support

When reporting issues, include SDK version, framework version, minimal reproduction steps, and expected vs. actual behavior.

Contributing

  1. Fork dotCMS/core
  2. Create a feature branch
  3. Commit your changes
  4. Open a Pull Request

Please ensure your code follows the existing style and includes appropriate tests.

Before any pull requests can be accepted, an automated tool will ask you to agree to the dotCMS Contributor's Agreement.

Licensing

dotCMS is available under either the Business Source License 1.1 (BSL) or a commercial license.

Under the BSL, dotCMS can be used at no cost by individual developers, small businesses or agencies under $5M in total finances, and by larger organizations in non-production environments. Every BSL release automatically converts to GPL v3 four years after its release date. For full terms and FAQs, visit dotcms.com/bsl and dotcms.com/bsl-faq.

Production use in larger organizations, along with access to managed cloud, SLAs, support, and enterprise capabilities, is available under a commercial license from dotCMS. For details on commercial plans, features, and support options, see dotcms.com/pricing.

版本与发布记录

@dotcms/experiments 共发布 335 个版本,首次发布于 2024/04/13;过去 12 个月发布了 193 个版本。

版本发布日期距今
26.11.17-1latest2026/11/17今天
26.11.2-3-next.3107next2026/11/161 天前
26.11.2-3-next.30882026/11/135 天前
26.11.2-32026/11/125 天前
26.11.11-12026/11/116 天前
26.11.10-22026/11/117 天前

其他发布通道:alpha → 0.0.1-alpha.62,next → 26.11.2-3-next.3107。

关于 @dotcms/experiments 的常见问题

@dotcms/experiments 是什么?

Official JavaScript library to use Experiments with DotCMS.

如何安装 @dotcms/experiments?

在项目目录运行 npm install @dotcms/experiments,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(>=18)、react-dom(>=18)、@dotcms/uve(26.11.17-1)、@dotcms/react(26.11.17-1)、@dotcms/types(26.11.17-1)、@dotcms/client(26.11.17-1)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@dotcms/experiments 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@dotcms/experiments 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@dotcms/experiments 可以商用吗?

@dotcms/experiments 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@dotcms/experiments 的下载量有多少?

根据 npm 官方下载统计,@dotcms/experiments 在 2026/10/13 – 2026/11/11 这 30 天内被下载 5,049 次,日均约 168 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@dotcms/experiments 还在维护吗?

最新版本 26.11.17-1 发布于 2026/11/17(今天);至今共发布 335 个版本,其中过去 12 个月发布了 193 个;首次发布于 2024/04/13。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。