The snippet is a self-contained JavaScript file that contains your project’s experiment configuration (the “datafile”), targeting rules, and the Optimizely client runtime. When it executes in the browser, it evaluates which experiments are active, buckets the visitor, and applies variation changes.
Optimizely updates the snippet whenever you publish changes to experiments. Self-hosting means you are responsible for fetching these updates and deploying them to your infrastructure.
import requests
PROJECT_ID = 'YOUR_PROJECT_ID'
SNIPPET_URL = f'https://cdn.optimizely.com/js/{PROJECT_ID}.js'
response = requests.get(SNIPPET_URL)
if response.status_code == 200:
with open('public/optimizely-snippet.js', 'w') as f:
f.write(response.text)
print('Snippet downloaded successfully')
else:
print(f'Download failed: {response.status_code}')
Module format note: The Node.js example above uses CommonJS (require). If your project uses ES modules, replace require with import:
import fs from'fs';
import https from'https';
Python dependency: The Python script requires the requests library. Install it with pip install requests if it is not already in your project dependencies.
Self-hosting the snippet shifts operational responsibility from Optimizely to your team. Before committing, consider the ongoing costs:
Pipeline monitoring — Your update automation (webhook or cron) must be monitored. If it fails silently, your snippet becomes stale and experiments stop reflecting changes made in the Optimizely app.
CDN purge failures — A failed cache purge means visitors continue receiving an outdated snippet. Set up alerts on purge failures for your CDN provider and have a manual purge runbook ready.
Staleness detection — Add a monitoring check that compares the snippet version on your CDN against the latest version on cdn.optimizely.com. Alert if the versions diverge for more than your acceptable threshold (e.g., 15 minutes for webhook setups, or 2x your polling interval for cron setups).
On-call ownership — Someone on your team needs to be responsible for snippet freshness. If an experiment launch is blocked because the snippet did not update, the team needs a clear escalation path.
If the operational overhead outweighs the benefits, the default Optimizely-hosted snippet is a reliable alternative.