Skip to main content

Install the Optik SDK

Add A/B testing to your website with a single script tag. The Optik SDK is under 5KB gzipped, loads asynchronously, and applies experiments before first paint.

<5KB
Gzipped size
Async
Non-blocking load
Zero
Dependencies

Quick Start

One script tag. That is it.

Copy and paste this snippet into your HTML before the closing </head> tag. Replace the project key with your own from the Optik dashboard.

HTML
<!-- Paste before </head> -->
<script
  src="https://cdn.optik-app.com/sdk/optik.js"
  data-project="pk_your_project_key"
  defer
></script>

Note: Replace pk_your_project_key with your actual publishable key from dashboard.optik-app.com. You can find it in Project Settings.

That is it. The SDK loads automatically and applies any active experiments to the page. No additional configuration is required for most use cases.

Step-by-Step

Detailed installation walkthrough

Follow these four steps to install the Optik SDK and start running A/B tests on your website. The entire process takes less than two minutes.

01Sign up and create a project

Go to dashboard.optik-app.com and create a free account. Once logged in, create a new project for the website where you want to run experiments. Each project corresponds to a single website or application.

02Copy your publishable key

Navigate to Project Settings in the dashboard. Your publishable key is displayed at the top of the settings page. It starts with pk_ and is safe to include in client-side code. It identifies your project but cannot be used to modify experiments or access your account.

03Add the script tag

Paste the following script tag into your HTML, ideally inside the <head> section before the closing </head> tag. The defer attribute ensures the SDK loads without blocking page rendering.

<script
  src="https://cdn.optik-app.com/sdk/optik.js"
  data-project="pk_abc123..."
  defer
></script>

04Verify the installation

Open your website in a browser and check the developer console (F12 or Cmd+Option+J). You should see a log message from [optik] confirming the SDK has loaded. You can also append ?optik_debug=true to your URL to see the in-page debug panel with experiment details.

Console output
[optik] SDK initialized (project: pk_abc123)
[optik] Config loaded (2 active experiments)
[optik] Assigned: homepage-headline variant-b

Installation Methods

Choose your platform

The Optik SDK works on any website. Pick the installation method that matches your stack.

Script Tag

Recommended

The simplest and most reliable method. Works on any website regardless of framework.

HTML
<!-- Add to your <head> section -->
<script
  src="https://cdn.optik-app.com/sdk/optik.js"
  data-project="pk_your_project_key"
  defer
></script>

Google Tag Manager

If you manage scripts through Google Tag Manager, add the SDK as a Custom HTML tag.

HTML
<!-- GTM Custom HTML Tag -->
<script
  src="https://cdn.optik-app.com/sdk/optik.js"
  data-project="pk_your_project_key"
  defer
></script>

<!--
  1. Create a new Custom HTML tag
  2. Paste the script tag above
  3. Set trigger to "All Pages"
  4. Publish your container
-->

Next.js / React

Use the Next.js Script component for optimized loading. For plain React SPAs, add the script tag to your index.html.

TSX
// In your layout.tsx or _document.tsx
import Script from 'next/script'

export default function RootLayout({ children }) {
  return (<html>
    <body>
      {children}
      <Script
        src="https://cdn.optik-app.com/sdk/optik.js"
        data-project="pk_your_project_key"
        strategy="afterInteractive"
      />
    </body>
  </html>)
}

Shopify

Install the Optik app from the Shopify App Store. The SDK is automatically injected into your theme -- no manual code changes needed.

Liquid
<!-- If you prefer manual installation: -->
<!-- Edit theme.liquid and add before </head> -->

<script
  src="https://cdn.optik-app.com/sdk/optik.js"
  data-project="pk_your_project_key"
  defer
></script>

WordPress

Add the SDK via your theme customizer, a header scripts plugin (such as Insert Headers and Footers), or by editing your header.php template directly.

HTML
<!-- Option 1: Theme Customizer or Header Scripts plugin -->
<!-- Paste this into the "Header Scripts" field: -->

<script
  src="https://cdn.optik-app.com/sdk/optik.js"
  data-project="pk_your_project_key"
  defer
></script>

<!-- Option 2: Edit header.php directly -->
<!-- Add the same tag before wp_head() closes -->

Configuration

Script tag attributes

The SDK is configured entirely through HTML data attributes on the script tag. No JavaScript initialization code is needed.

data-projectRequiredstring

Your publishable project key, found in Project Settings on the dashboard. Starts with pk_. This identifies your project and determines which experiments to load.

Default: None

data-apiOptionalstring

Custom API endpoint URL. Only needed if you are using a self-hosted Optik instance or a custom proxy. Most users should omit this attribute.

Default: api.optik-app.com

Full example with all attributes
<script
  src="https://cdn.optik-app.com/sdk/optik.js"
  data-project="pk_abc123def456"
  data-api="https://api.optik-app.com"
  defer
></script>

Verification

Verify and debug your installation

Three ways to confirm the SDK is installed correctly and inspect experiment assignments.

Debug mode

Append ?optik_debug=true to any page URL to activate the in-page debug panel. The panel shows active experiments, your variant assignments, targeting rule matches, and DOM mutations applied by the SDK.

https://yoursite.com?optik_debug=true

Chrome DevTools extension

Install the Optik DevTools extension from the Chrome Web Store to inspect experiments directly in Chrome DevTools. The extension adds an "Optik" panel where you can view experiment state, force variant assignments for QA testing, and monitor SDK event logs without modifying URLs.

Console logging

When debug mode is active, the SDK logs detailed information to the browser console. Look for messages prefixed with [optik]. These include initialization status, config fetches, experiment assignments, and conversion events.

[optik] SDK initialized (v1.2.0, project: pk_abc123)
[optik] Config fetched (2 experiments, ETag: "a1b2c3")
[optik] Experiment: homepage-headline
[optik]   Assigned variant: variant-b
[optik]   Mutations applied: 3
[optik] Impression tracked: homepage-headline

Under the Hood

How the SDK works

Technical details for developers who want to understand the SDK internals.

Asynchronous loading

The SDK loads with the defer attribute and never blocks page rendering. Your site remains fast regardless of SDK load time.

Config fetching with ETag caching

On first load, the SDK fetches experiment configuration from the API. Subsequent visits use ETag-based caching: the browser sends a conditional request, and the API returns a 304 Not Modified if nothing has changed, minimizing bandwidth.

Flicker-free DOM mutations

Experiment variants are applied via requestAnimationFrame in a single batch. The SDK modifies the DOM before the browser paints, preventing any visible flash of original content.

Impression and conversion tracking

The SDK automatically tracks experiment impressions when a variant is assigned. Conversion events are sent via the Beacon API for reliable delivery, even when the user navigates away.

Anonymous visitor identification

Each visitor is assigned a random UUID stored in localStorage (optik_vid). This ID is not linked to any personal information and is used solely to maintain consistent variant assignments across page views.

Graceful failure

If the API is unreachable or the SDK encounters an error, it fails silently. Your website continues to work normally with the original content displayed. No exceptions are thrown to the host page.

Advanced

Advanced usage

The SDK exposes a JavaScript API for programmatic control over experiments, custom event tracking, and QA tools.

Custom event tracking

Track custom conversion events from JavaScript. Events are automatically associated with the visitor's active experiment assignments.

JavaScript
// Track a purchase event with metadata
window.__CUXP__?.track('purchase', {
  value: 49.99,
  currency: 'USD'
});

// Track a simple event
window.__CUXP__?.track('clicked_signup');

Forced variants for QA

Override variant assignments for testing by adding a query parameter to your URL. This forces a specific variant for the current session without affecting production traffic.

// Force a specific variant via URL parameter
https://yoursite.com?optik_force=homepage-headline:variant-b

// Force multiple experiments at once
https://yoursite.com?optik_force=homepage-headline:variant-b,cta-color:red

Visitor opt-out

Allow visitors to opt out of all experiments. When the opt-out flag is set, the SDK will not assign variants or track any events for that visitor.

// Opt a visitor out of all experiments
localStorage.setItem('optik_optout', 'true');

// Re-enable experiments for this visitor
localStorage.removeItem('optik_optout');

Integrations

Google Analytics 4 integration

Send experiment impressions and conversion events directly to your GA4 property. The integration runs server-side via the Measurement Protocol, so it adds zero latency to your website and zero bytes to the SDK bundle.

What you need

Two values from your Google Analytics admin panel

1. Measurement ID

Your Measurement ID identifies which GA4 property receives the events. It looks like G-XXXXXXXXXX.

To find it:

  1. Open Google Analytics
  2. Click Admin (gear icon, bottom left)
  3. Under the Property column, click Data Streams
  4. Select your web data stream
  5. Copy the Measurement ID shown at the top right

2. API Secret

The API Secret authenticates server-side requests to the GA4 Measurement Protocol. It is not the same as your Google Cloud API key.

To find it:

  1. From the same Data Stream detail page above, scroll down
  2. Click Measurement Protocol API secrets
  3. Click Create to generate a new secret (give it a name like "Optik")
  4. Copy the Secret value

Connect GA4 in Optik

1. In the Optik dashboard, go to Integrations and click Add Integration.

2. Select Google Analytics 4 as the type and paste your Measurement ID and API Secret.

3. Choose which events to forward (impressions, conversions, or both), then save.

Zero performance impact: GA4 events are sent server-side using a fire-and-forget pattern. The integration runs asynchronously on the Optik backend after your API response has already been sent. It never touches the browser, never adds latency to your pages, and never increases your SDK bundle size.

Troubleshooting

Common issues and solutions

If something is not working as expected, check these common issues first.

SDK not loading

Verify the script tag is placed inside the <head> section. Check that the src URL is correct (https://cdn.optik-app.com/sdk/optik.js) and that your publishable key starts with pk_. If your site uses a Content Security Policy, add cdn.optik-app.com to your script-src directive.

Experiments not showing

Confirm the experiment status is set to "running" in the dashboard. Check that the targeting rules match the current page URL. Try enabling debug mode (?optik_debug=true) to see which experiments are loaded and why they may not be activating. Also verify your project key matches the project containing the experiment.

Flicker on page load

Ensure the script tag is placed in the <head> section with the defer attribute, not at the end of <body>. The SDK needs to load early enough to apply mutations before first paint. If the script is loaded too late (e.g., injected by a tag manager after DOMContentLoaded), there may be a brief flash of original content.

Content Security Policy (CSP) blocking the SDK

Add the following to your CSP headers: cdn.optik-app.com in the script-src directive (to load the SDK bundle) and api.optik-app.com in the connect-src directive (to allow config fetches and event tracking). Example: script-src 'self' https://cdn.optik-app.com; connect-src 'self' https://api.optik-app.com;

Still stuck? Reach out to us at [email protected] with your project key and a description of the issue. We typically respond within a few hours.

Ready to run your first experiment?

Create your free account and go from install to running in under two minutes.