Experiment Quick Start
Experiment is a workflow-driven behavioral experimentation platform that speeds up creating variants of features and websites for testing.
With Experiment, you can modify and configure product experiences for unique audiences through:
- Product experimentation: Run experiments and A/B tests to onboard new users, reduce friction for checkout experiences, roll out new features, and more.
- Progressive feature delivery: Pre-plan and stage new features for beta testers, a percentage of your users, or specific target audiences.
- Dynamic in-product experiences: Deploy and adapt custom experiences at scale.
- Web experimentation: Perform A/B testing directly on your website.
Experiment supports experimentation through either Feature Experiment or Web Experiment:
- Feature Experiment runs experiments through feature flags. Feature flags are switches that let you modify your product's experience without changing code.
- Web Experiment runs experiments through the Visual Editor. The Visual Editor places a dynamic, customizable layer over your existing website. Through the Visual Editor, you can customize any element of your website without changing the site's underlying code or structure.
For more information about the use cases for each type of experimentation, go to Feature and Web Experiment use cases.
This page splits the quick start into Feature Experiment and Web Experiment. Select the tab for the experiment type you want to set up.
This quick start guide contains only the basic information needed to implement Experiment. Review the entire set of Experiment documentation to understand the full complexity of the product.
Experiments and feature flags use the Amplitude Experiment SDK or REST API to communicate with Amplitude Experiment.
Setting up an experiment is a multi-stage process with these procedures:
- Install and set up SDKs and deployments.
- Create feature flags.
- Select the deployment and create a payload.
- Create variations and send payloads.
- Design experiments.
Before you begin
Before you start using experiments:
- Confirm you have developer write access to the Experiment SDK.
- Confirm you have access to the Experiment feature.
- Confirm you have developer access to the application where you integrate your feature flags.
Set up the SDK
Install the Amplitude SDK with the Experiment client. For example:
npm install @amplitude/analytics-browser @amplitude/experiment-js-client
import * as amplitude from "@amplitude/analytics-browser";
import { Experiment } from "@amplitude/experiment-js-client";
amplitude.init("AMPLITUDE_API_KEY");
const experiment = Experiment.initialize("DEPLOYMENT_API_KEY");
await experiment.start();
Set up a deployment
Experiment uses the same projects as Amplitude Analytics. As a best practice, create one project for each product and each environment. Because flags, experiments, and deployments only exist within a single project, you must duplicate these objects across projects within the same product.
In Amplitude Experiment, a deployment serves a group of flags or experiments for use in an application. Each project has a deployment using the project API key as the deployment key, available by default. On creation, Experiment assigns a randomly generated deployment key to each deployment. Experiment uses the deployment key to identify the deployment and authorize requests to the evaluation servers.
Client vs. server deployments
Deployments are either client or server deployments. Use client-side deployments to initialize client-side SDKs, and server-side deployments to initialize server-side SDKs or authorize requests to the Evaluation API.
Deployments belong to Amplitude Analytics projects, and a project can have multiple deployments. Amplitude recommends that you name deployments after the platform (client-side) or service (server-side) to which Experiment serves variants (for example: android, ios, web). The default project API key deployment is useful for getting started. Use explicit deployments for each platform or service in larger organizations or teams that may share the same Amplitude project across multiple platforms for the same application. Each deployment receives a unique key for use in your application.
To create a deployment
- Go to Experiments > Deployments.
- Select Create Deployment.
- Select the project you want from the dropdown list.
- Name your deployment.
- Select whether your deployment is for Client or Server.
- Select Create a Deployment. For full details, go to Configure your experiment.
Create a new flag
A flag lets you enable or disable a function or feature in your product without deploying new code each time. Flags drive both experiments and feature rollouts. Flags work well for launching experiments and ending them after you collect enough data, and for rolling out new features (and rolling them back, if needed).
To create a new feature flag
- Go to Experiment > Feature Flags.
- Select Create Feature Flag.
- In the Create Flag section, select the project you want from the dropdown list, then give your flag a name. Amplitude Experiment generates the flag key from the name you choose. The flag key is an identifier for the flag used in your codebase.
- Specify the evaluation mode for your experiment. Select either Remote or Local.
- Specify the bucketing unit you want to use for this experiment.
The best bucketing unit is typically the user. In some B2B use cases, you might want to use company ID or city as the bucketing unit. For example, bucketing by company ID ensures all users in a particular company have the same user experience. Confirm the Stable Unit Treatment Value Assumption holds for whichever unit you choose.
- Select Create. Experiment opens a blank template for your flag.
- Choose the deployment you want from the Deployment dropdown menu.
- (Optional) Select Advanced Settings to modify the bucketing salt options.
If you change the bucketing salt, users can switch between variants in your experiment. For that reason, Amplitude recommends not changing the bucketing salt unless you know what you’re doing. For more information, go to How randomization works in Amplitude Experiment.
Create variations
A variant exists within a flag or an experiment, and represents a variable experience for a user. Variants comprise the A/B changes you want to test. All feature flags must contain at least one variant. You can add as many variants as you want to a flag.
To add a variant
- Go to your Experiment > Feature Flags and select your flag.
- In the Variants section, select the Plus icon to create a variant.
- Enter the name, value, and description of your variant.
- Select Apply.
You can send a payload with your variant. A payload is a JSON-coded set of variables that can remotely change flags and experiments without a manual code change. Because you can send a payload with your control, you don’t need to create a variant for the control itself.
Add JSON content to the Payload field when creating a variant. Payload content resembles:
{
"layout": "cards",
"titlePosition": "above",
"gradient": false,
"showDescription": true,
"cardCount": 3
}
Add targeting to the flag
In the Assignment section, define the user segments you want to experience your new feature. Defining a user segment limits your rollout to users in specific geographical locations, certain demographic groups, or who meet certain usage thresholds in your product (for example, power users). For more information on segmenting, go to Define your audience.
To add targeting
- Specify the percentage of users who receive the variant.
- To define a user segment, go to the Rule Based User Segments section and select Segment 1. Then follow the same steps you use to build a user segment in Amplitude Analytics.
Finalize the flag
After you set up the flag, associate it with a deployment, set up your variants or payloads, and target your users, finalize the feature flag. Finalizing the flag activates the flag and makes it available.
To finalize a feature flag
- Go to your feature flag.
- Select Activate flag.
Design the experiment
You can create an experiment directly or convert an existing flag to an experiment.
When designing your experiment:
- Set metrics for the experiment.
- Set up any further variations and payloads.
Adding goals (or metrics) lets you track the success rate of your experiment. All experiments should have at least one metric. Tell Amplitude Experiment what you want your primary metric to be, and define any secondary metrics. The primary metric determines whether Amplitude accepts or rejects your hypothesis, and therefore whether your experiment succeeded or failed.
To add metrics
- Open your experiment and go to the Metrics section.
- Select your recommended metric from the Metric dropdown or create a custom metric.
- Select the metric type using "should" or "should not":
- "Should": A Success metric states the goal changes by the goal amount and direction.
- "Should not": A Guardrail metric states the goal doesn’t change by the goal amount and direction.
- Specify whether you expect the metric to increase or decrease.
- (Optional) Set the minimally acceptable goal for the experiment, also known as the minimum detectable effect. The minimum detectable effect is the minimum difference between the control and the variant for the experiment to count as a positive result.
- To add secondary metrics, select Add Metric and repeat this process for each additional metric you want to include.
To add more variations and payloads
To create more variations and payloads, repeat the steps in Create variations in your flag.
Start your experiment
After you finish designing your experiment, select Start Experiment to begin.
Code examples
The following code examples show the code for a feature flag and a JSON payload.
import { useState, useEffect } from 'react';
import { getBlogLayoutFlag } from '../services/featureFlags'; // Adjust to wherever you fetch your Amplitude flag
import type { BlogPost } from '../types';
type LayoutFlag = {
layout: 'cards' | 'list' | 'carousel';
titlePosition: 'above' | 'below' | 'center';
gradient: boolean;
showDescription: boolean;
cardCount: number;
};
export default function BlogPostLayoutClient({ posts }: { posts: BlogPost[] }) {
const [layoutFlag, setLayoutFlag] = useState<LayoutFlag | null>(null);
useEffect(() => {
getBlogLayoutFlag().then((flag) => {
console.log(':magic_wand: Received Flag from Amplitude:', flag);
if (flag) {
setLayoutFlag(flag);
} else {
console.log(':warning: No flag returned, falling back to default layout');
setLayoutFlag({
layout: 'cards',
titlePosition: 'above',
gradient: false,
showDescription: true,
cardCount: 3,
});
}
});
}, []);
if (!layoutFlag) {
// You might render a loader here
return null;
}
// Render your posts according to layoutFlag...
return (
<div>
{/* e.g. layoutFlag.layout === 'cards' ? <CardGrid posts={posts} /> : ... */}
</div>
);
}
// services/featureFlags.ts
import { experiment } from '@amplitude/experiment-js'; // adjust import to your SDK
import type { LayoutFlag } from '../types'; // reuse the same LayoutFlag type
export const getBlogLayoutFlag = async (): Promise<LayoutFlag> => {
try {
// In dev, clear any stale flags
if (process.env.NODE_ENV === 'development') {
localStorage.clear();
console.warn('Cleared localStorage in dev mode');
}
// Initialize the experiment SDK
await experiment.start();
// Grab the variant for our blog layout test
const variant = experiment.variant('blog_post_layout');
console.log(':movie_camera: Full Variant Object:', variant);
// Some payloads come in `payload`, some in `value`
const value = variant?.payload ?? variant?.value;
console.log('Cleaned Flag Payload:', value);
// If there's no usable object, fall back to defaults
if (!value || typeof value !== 'object' || Object.keys(value).length === 0) {
console.warn('No valid layout flag found, using fallback layout');
return {
layout: 'carousel',
titlePosition: 'above',
gradient: false,
showDescription: true,
cardCount: 3,
};
}
// Otherwise assume it's Amplitude's LayoutFlag shape
return value as LayoutFlag;
} catch (error) {
console.error('Error fetching blog layout flag:', error);
// On error, also fall back
return {
layout: 'carousel',
titlePosition: 'above',
gradient: false,
showDescription: true,
cardCount: 3,
};
}
};
Web Experiment requires you to implement the Web Experiment script on your site before you begin.
Paste the script into the <head> element of your site, as high as possible to avoid flickering.
The script tracks impression events with the Browser SDK already installed on your site, or with a third-party analytics SDK.
Add the experiment script
Replace AMPLITUDE_API_KEY with your project's API key in one of the following synchronous scripts, depending on your region:
<script src="https://cdn.amplitude.com/script/AMPLITUDE_API_KEY.experiment.js"></script>
<script src="https://cdn.eu.amplitude.com/script/AMPLITUDE_API_KEY.experiment.js"></script>
Security headers
Your site may need the following security header adjustments to work with Web Experiment.
If your site defines the script-src content policy directive, add *.amplitude.com and unsafe-inline to the policy values. These changes enable loading the Web Experiment script and visual editor on your site.
Content-Security-Policy: script-src *.amplitude.com unsafe-inline;
If your site sets the Cross-Origin-Opener-Policy header, you can either remove the header or set it to unsafe-none. This setting allows the visual editor to load on your site.
Cross-Origin-Opener-Policy: unsafe-none
Set up a web experiment
In Amplitude Experiment, go to Experiments > Create Experiment > Web Experiment.
In the New Experiment modal, give your experiment a name. Enter the URL of a page this experiment targets. Amplitude must be instrumented on that page, and select the appropriate project from the dropdown. Amplitude uses this URL to create your first Page.
If the script is present on the page you specified, Amplitude Experiment opens the page in the Visual Editor as a new variant in your experiment.
You have two options for the treatment variant action: element changes or URL redirect.
If the script isn’t present on the page you specify, or if you have an ad blocker or other privacy extension enabled, Amplitude Experiment can’t open the Visual Editor. Amplitude Experiment opens the Site Setup panel and prompts you to implement the script.
To change text, colors, or other elements of the page’s UI, select Element Changes.
Select the element you want to change.
The editing toolbar opens beside the selected element with quick actions such as editing the element’s content or moving the element.
Selecting the expand icon opens the drawer, which lets you edit CSS style properties. When you’re done, select Apply.
Repeat this process for each element you want to change for your experiment.
If needed, select + to add another variant.
When you’re done, select Continue.
In the Pages tab, configure which Pages your experiment targets. You can create new Pages or reuse existing saved Pages. If you target only the page you set on creation, you can skip this step. From the Include pages where dropdown, specify how you want Amplitude Experiment to identify these pages.
Use the same pattern to exclude the experiment from the pages you select. Learn more about managing Pages for precise experiment targeting.
Next, target the users you want to include in this experiment. If you’re familiar with feature experiment targeting, note that Web Experiment audience targeting works differently.
The Advanced tab provides several additional options for your experiment.
When you’re ready, select Save and Close to finish creating your Web Experiment.
Create a new run of an existing experiment
If you have an experiment that you need to re-run, refer to New Experiment Run.
Test and preview your web experiment
Before running your web experiment, Amplitude recommends that you test and preview each variant. When you’re ready:
- Select Test & Preview. This action puts your experiment in test instrumentation mode, but doesn’t start your experiment. Only users who open the page with the preview link can view your changes.
- In the modal, select Preview to open a new tab that applies the changes you made for that variant. Select the chain link icon to copy the URL so you can share it with others.
Test each variant at least one time, preferably more. Test each variant on more than one page if your experiment targets multiple pages.
If your changes aren’t apparent, you may need to wait up to 60 seconds for caches to refresh. If the changes don’t appear correctly after that time, the configuration may have an issue.
Ad blockers
Ad blocking plugins or extensions may prevent you from testing and previewing your experiment.
Add actions
Actions define how variants modify your site. Actions relate to variants rather than a specific page, and apply to specific Pages to control exactly where they take effect.
Experiment applies variant actions during evaluation. Evaluation runs on the initial page load and any time state pushes to or pops from the session history. History state changes also cause the SDK to revert all applied element change and custom code actions before reevaluating and reapplying actions with the updated page in mind.
Actions include:
For more information about each action, refer to the preceding links.
Action examples
Generative AI like ChatGPT or equivalents can create HTML and CSS for simple elements. ChatGPT generated the following modal and banner examples, which Amplitude then modified.
Insert an element
To insert an element onto your page, follow this pattern.
Write the HTML and CSS for the element you want to add to the page.
Identify the selector of the parent element you want to insert your new element into. The parent element is often the
body.Paste the following JavaScript code, and update
PARENT_SELECTORwith the parent element selector from step 2.jsutils.waitForElement("PARENT_SELECTOR").then(function (e) { e.appendChild(html); utils.remove = function () { html.remove(); }; });
To insert your element into the parent element at a specific position, use insertBefore() instead of appendChild().
Add a banner
This example adds a discount code banner to the top of the page.
utils.waitForElement("body").then(function (e) {
e.insertBefore(html, e.firstChild);
utils.remove = function () {
html.remove();
};
});
.announcement-banner {
background-color: #fafafa;
color: #333;
padding: 10px;
text-align: center;
font-family: Arial, sans-serif;
border-bottom: solid #e5e5e5;
border-bottom-width: 1px;
}
.announcement-banner p {
margin: 0;
font-size: 16px;
}
<div class="announcement-banner">
<p>🎉 Big Sale: Get 25% off on all items! Use code <strong>SAVE25</strong></p>
</div>
Work with pages
In a Web Experiment, Pages control where your experiment variants apply on your site. Pages scope experiments to specific URLs, which lets you run tests on targeted pages without affecting unrelated parts of your site.
A Page defines the conditions under which a web experiment applies to your site, and includes:
- A unique name.
- URL targeting conditions.
- A Visual Editor URL to help preview the experiment.
Create a page
When you create a new Web Experiment, specify a page by:
- Manual URL input: Enter a specific URL to define the page.
- Import a saved page: Select a page from a previous experiment.
After you add the page, continue with experiment setup, or go directly to the Visual Editor.
Update a page or create another
To update a page definition, navigate to the Pages tab of the Experiment Setup flow, or select the pencil icon on the Pages section of the Settings tab. From there, rename the page, update its Visual Editor URL, or update the page targeting rules.
Page targeting rules
- URL Matches
- Description: Match the page URL, ignore query parameters or hash fragments.
- Examples:
https://example.com/pricing- ✅ https://example.com/pricing#details
- ❌https://example.com/pricing/enterprise
- URL Matches Exactly
- Description: Match the full page URL exactly.
- Examples:
https://example.com/pricing?utm_source=facebook- ❌https://example.com/pricing
- ❌ https://example.com/pricing?utm_source=tiktok
- URL Matches Pattern
- Description: Match the full page URL, including wildcards (
*). - Examples:
https://example.com/blog/*- ✅ https://example.com/blog/my-first-post
- ✅ https://example.com/blog/my-second-post#get-started
- Description: Match the full page URL, including wildcards (
- URL Contains
- Description: Match the full page URL, where the URL contains a specific substring.
- Examples:
/blog/my-first- ✅ https://example.com/blog/my-first-post
- ❌ https://example.com/blog/my-second-post
- URL Starts With
- Description: Match the full page URL, where the URL starts with an exact substring.
- Examples:
https://example.com/blog- ✅ https://example.com/blog/my-first-post
- ❌ https://example.com/pricing
- URL Ends With
- Description: Match the full page URL, where the URL ends with an exact substring.
- Examples:
/blog/my-first-post- ✅ https://example.com/blog/my-first-post
- ❌ https://example.com/blog/my-first-post#get-started
- URL Matches Regex
- Description: Match the full page URL with a regular expression you define.
- Examples:
Manage page scope for variants
In a web experiment, you can scope each variant to a specific page so the variant’s changes apply only where you intend. This rule applies to all variant types.
Visual editor
When you use the Visual Editor to make changes, for example text edits or style updates, those changes associate with the page you select during the preview session. For each change, specify the page or pages it applies to.
Page scope lets you:
- Assign updates or changes to a specific page.
- Avoid applying the same change across all views.
- Maintain better isolation and clarity across your experiment setup.
Double-check the page scope
Check the page scope for each change to ensure you don’t introduce cross-page conflicts or unintended edits.
Custom code
When you add custom code or URL redirects as variants, you can explicitly define which page or pages the variant applies to.
This flexibility lets you create a single experiment that includes custom code with different behaviors, depending on the active page.
Targeting
Web Experiments target both pages and audiences. Amplitude evaluates page targeting first, and then audience targeting. Both targeting methods evaluate locally in the browser when the page first loads.
Web Experiments use Pages to precisely control where experiment variants apply on your website. Pages define the conditions under which a web experiment applies, including targeting conditions to match specific URLs and visual editor URLs for previewing experiments.
Audience targeting
By default, a new Web Experiment targets all users. Audience targeting lets you target specific users for your experiment. Users who aren’t targeted in the experiment receive the default experience and don’t count toward analysis.
If any segments match, Amplitude buckets that user into a variant based on the configured rollout and variant distribution. For a segment to match, the user must meet all conditions you set. For more details, go to Web Experiment targeting.
Web Experiment performance
Web Experiment intentionally minimizes its impact on page performance.
Script size
The Web Experiment script is dynamic and includes all your experiment configurations to avoid multiple synchronous downloads. The script size starts with a base size and scales with each experiment.
| Uncompressed | Compressed | |
|---|---|---|
| Base script | 79KB | 20KB |
| Per-flag size | ~1KB | ~100B |
To avoid continually increasing script sizes, deactivate or archive experiments when they’re complete.
Custom code impact on flag size
Custom code increases the size of a flag’s code because of the size of the custom code itself.
Caching
Web Experiment uses two caching layers: CDN and browser. These layers help provide more reliable script delivery to your site.
CDN cache
Amplitude caches the Web Experiment script on a CDN. When a user requests the script, the user’s browser loads the script from the CDN if another user loaded it in the same geographic area. The CDN cache has a max age of one minute, and serves stale content while the script reloads for up to one hour. The script serves a stale response if the origin returns an error for the maximum amount of time possible.
The cache control response header that configures CDN caching is:
max-age=60,stale-while-revalidate=3600,stale-if-error=31536000
Browser cache
The browser cache serves the Web Experiment script without making a network request for 60 seconds, or for the maximum amount of time if the server returns an error. The browser cache serves the script from memory (0ms latency) if a user loads multiple pages on your site, or reloads the same page within a one minute window.
The cache control response header that configures browser caching is:
max-age=60,stale-while-revalidate=3600
Was this helpful?
For AI agents: a documentation index is available at /docs/llms.txt. Append .md to any page URL for markdown, or send Accept: text/markdown.