Implementing Convert's Full Stack JavaScript SDK: Real-World Examples
Master Convert's JavaScript Full Stack SDK with real-world A/B testing examples for pricing, trials, payments, analytics, and persistent storage.
🚀 In This Article You Will:
- Understand the Importance of Convert's Full Stack JavaScript SDK
- Get and manage SDK Keys inside the Convert app (Public vs Authenticated)
- Check the Prerequisites for Implementation
- Install the Convert JavaScript SDK
- Run an A/B Test for Subscription Tier Pricing
- Optimize Free Trial Length for Higher Conversions
- See More Examples
- Follow Best Practices for Reliable Experimentation
- Apply Key Takeaways to Your Own Applications
Introduction
Convert's JavaScript Full Stack SDK provides a powerful way to implement experimentation and feature management in your applications. This guide presents five real-world implementation examples to help you understand how to effectively use the SDK for various business scenarios.
These examples demonstrate how to properly implement Convert's SDK for:
- Subscription pricing tests
- Trial period experiments
- Payment recovery workflows
- Persistent data storage
- Analytics integration
Each example includes detailed business context, implementation code, and best practices.
Prerequisites
- Before diving into the examples, ensure you have:
- A Convert account with access to the Full Stack product
- Node.js installed in your environment
- Basic knowledge of JavaScript and async/await patterns
- Access to the SDK Config & Keys area in your Full Stack project (to create and manage SDK keys)
When using the SDK:
- Use Public SDK keys in browser/client-side environments only.
- Use Authenticated SDK keys (which include a secret) only in secure server-side or edge environments. Never expose the SDK secret to the browser.
Installation
Install the Convert JavaScript SDK using npm:
npm install @convertcom/js-sdk
Or using yarn:
yarn add @convertcom/js-sdk
Getting Your SDK Key (and Secret) from Convert
Before you initialize the SDK, you need an SDK key created in your Convert project:
- In the Convert app, open your Full Stack project.
- Go to Configuration → SDK Config & Keys.
- Open the SDK Keys tab:
- You’ll see a Default Public key at the top. This key is automatically created, has the format
accountId/projectId, and is labeled Default. It is always Public and can be enabled/disabled, but its “default” status cannot be changed. - You can create additional SDK keys for specific environments or implementations by clicking Create New SDK Key.
- You’ll see a Default Public key at the top. This key is automatically created, has the format
- In the Create SDK Key dialog:
- Confirm Account ID and Project ID.
- Enter an SDK Key Name (for example,
SdkMainApporStagingKey). - Choose Environment:
Live,Staging, orAll (Live, Staging). - Choose SDK Key Type:
- Public – safe for client-side JavaScript.
- Authenticated – includes an SDK secret and is meant for secure server-side or edge usage.
- Click Create.
- After creation:
- For Public keys, you’ll see a dialog showing just the SDK Key, with a copy icon.
- For Authenticated keys, a dialog shows both SDK Key and SDK Secret with copy icons and a warning to store the secret securely. The secret is only fully visible at this time, so copy it to your secrets manager now.
The SDK Keys table lets you:
- Copy the key (and secret where relevant),
- Enable/disable a key,
- Delete non-default keys if they are no longer needed.
Permissions for SDK key management mirror your existing API key permissions: only users who can manage API keys can create, update, or delete SDK keys.
Using the SDK Config Tab with Your SDK Keys
The SDK Config tab under Configuration → SDK Config & Keys provides language-specific sample code snippets that are automatically populated with the SDK key you choose:
- Select your preferred SDK (e.g., JavaScript SDK, Python SDK, PHP SDK, etc.).
- Use the Select SDK Key dropdown to choose which key’s values should be injected into the sample code. Below the dropdown, you’ll see information such as:
- Environment: (e.g., Live, Staging, or All)
- Key Type: Public or Authenticated
- The sample code block beneath updates automatically. For Public keys, only the
sdkKeyvalue is injected. For Authenticated keys, the snippet also includes a placeholder for the SDK secret so you can wire it in on the server side.
You can copy this snippet and paste it into your application as a starting point, then adapt it to match the more advanced examples in this article.
Example 1: Subscription Tier Pricing Test
Business Context
The marketing team is implementing a strategic A/B test to determine if a premium pricing model can increase overall revenue without significantly reducing conversion rates.
The experiment compares:
- Control: $9.99/month subscription
- Variant: $12.99/month subscription with additional premium features
This test aims to evaluate price elasticity and determine the value perception of enhanced features among users.
In this example, CONVERT_SDK_KEY should be set to the SDK key value you copied from Configuration → SDK Config & Keys → SDK Keys. For a server-side implementation using an Authenticated key, also set CONVERT_SDK_SECRET and include the sdkKeySecret field as shown below:
Implementation
const Convert = require('@convertcom/js-sdk').default;
// SDK initialization
const convert = new Convert({
sdkKey: process.env.CONVERT_SDK_KEY,
sdkKeySecret: process.env.CONVERT_SDK_SECRET, // Authenticated keys only
environment: 'production'
});
// Get pricing plan based on experiment
async function getSubscriptionPlan(userId) {
try {
const experimentId = 'subscription_pricing_test';
const userContext = await convert.createContext({ userId });
const result = await userContext.runExperience(experimentId);
const variant = result.variationKey;
// Define plans
const pricingPlans = {
control: { price: 9.99, code: 'BASIC', features: ['Core Features', 'Basic Support'] },
variant_1: { price: 12.99, code: 'PREMIUM', features: ['Core Features', 'Priority Support', 'Enhanced Storage'] }
};
// Track exposure event
await userContext.trackConversion('experiment_exposed', {
conversionData: [{
experienceId: experimentId,
variationId: result.variationId
}]
});
return pricingPlans[variant];
} catch (error) {
console.error('Convert SDK Error:', error);
return { price: 9.99, code: 'BASIC', features: ['Core Features', 'Basic Support'] };
}
}
// Example implementation in pricing page route
app.get('/pricing', async (req, res) => {
const userId = req.session.userId;
const pricingPlan = await getSubscriptionPlan(userId);
res.render('pricing', {
monthlyPrice: pricingPlan.price,
planCode: pricingPlan.code,
features: pricingPlan.features
});
});
// Track conversion when user subscribes
app.post('/subscribe', async (req, res) => {
const userId = req.session.userId;
const selectedPlan = req.body.planCode;
const price = selectedPlan === 'PREMIUM' ? 12.99 : 9.99;
try {
const userContext = await convert.createContext({ userId });
await userContext.trackConversion('subscription_purchased', {
conversionData: [{
amount: price,
transactionId: orderId
}]
});
} catch (error) {
console.error('Failed to track conversion:', error);
}
res.redirect('/thank-you');
});
Key Implementation Notes
✔️ Consistent User Identification: Uses createContext() to establish user identity.
✔️ Experiment Variant Handling: Uses runExperience() to determine the assigned pricing tier.
✔️ Error Handling: Ensures a fallback to standard pricing if the SDK fails.
✔️ Conversion Tracking: Uses trackConversion() to track subscriptions.
✔️ SDK Key Management: The SDK is initialized with an SDK key created and managed under SDK Config & Keys; use a Public key for browser-based pricing pages and an Authenticated key for server-side initialization when extra security is required.
Example 2: Free Trial Length Experiment
Business Context
The growth team is testing whether extending the free trial period from 7 days to 14 days leads to higher conversion rates. The hypothesis is that a longer trial will allow users more time to see the product's value, ultimately increasing paid conversions.
As with the pricing example, CONVERT_SDK_KEY is taken from your SDK Keys tab. For a secure, server-side implementation using an Authenticated key, you can extend the initialization to include sdkKeySecret, keeping both the key and secret in environment variables or your secrets manager.
Implementation
const Convert = require('@convertcom/js-sdk').default;
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
// Initialize SDK
const convert = new Convert({
sdkKey: process.env.CONVERT_SDK_KEY,
sdkKeySecret: process.env.CONVERT_SDK_SECRET, // Authenticated keys only
environment: 'production'
});
// Handle trial signup
async function handleTrialSignup(userId, email) {
const experimentId = 'free_trial_length';
try {
const userContext = await convert.createContext({ userId });
const result = await userContext.runExperience(experimentId);
const variant = result.variationKey;
const trialDays = variant === '14-day' ? 14 : 7;
const customer = await stripe.customers.create({
email: email,
metadata: { userId, trialLength: trialDays }
});
const subscription = await stripe.subscriptions.create({
customer: customer.id,
items: [{ price: 'price_monthly_plan' }],
trial_period_days: trialDays
});
await userContext.trackConversion('trial_started', {
conversionData: [{
experienceId: experimentId,
variationId: result.variationId,
trialDays: trialDays,
subscriptionId: subscription.id
}]
});
return {
success: true,
trialDays,
subscriptionId: subscription.id
};
} catch (error) {
console.error('Trial signup failed:', error);
return handleFallbackTrialSignup(userId, email);
}
}
// Example usage in signup route
app.post('/signup', async (req, res) => {
const userId = generateUserId();
const email = req.body.email;
const result = await handleTrialSignup(userId, email);
res.json({
success: true,
trialEnds: new Date(Date.now() + (result.trialDays * 86400000))
});
});
Key Implementation Notes
✔️ Integrates Convert's SDK with Stripe for trial management
✔️ Uses runExperience() to get trial length variant
✔️ Tracks both trial start and conversion events
✔️ Implements fallback logic in case of errors
✔️ Uses the same SDK key and environment configuration pattern introduced in Example 1, ensuring consistent bucketing across pricing and trial flows.
More Examples
- Example 3: Payment Grace Period Workflow (Optimizing churn reduction with email vs. in-app notifications)
- Example 4: Implementing Persistent Storage (Ensuring users consistently receive the same experiment variant)
- Example 5: Analytics Integration (Syncing Convert's tracking with external analytics platforms)
🔝 Best Practices for Convert SDK Implementation
1. Error Handling & Fallbacks
Ensure robust error handling to maintain smooth user experiences:
try {
// Convert SDK code
} catch (error) {
console.error('Convert SDK error:', error);
// Fallback implementation
}
2. Environment Configuration
Set the correct environment for production or staging:
const convert = new Convert({
sdkKey: process.env.CONVERT_SDK_KEY,
environment: 'production'
});
If you use an Authenticated SDK key on the server, include sdkKeySecret as well and keep both values in a secure secrets store (for example, environment variables, a vault, or a secrets manager):
const convert = new Convert({
sdkKey: process.env.CONVERT_SDK_KEY,
sdkKeySecret: process.env.CONVERT_SDK_SECRET,
environment: 'production'
});
3. Consistent User Identification
Use a unique, stable user identifier to maintain experiment consistency:
const userContext = await convert.createContext({ userId: user.uniqueId });
4. Event Tracking Standards
Maintain structured event naming and data formats:
await userContext.trackConversion('purchase_completed', {
conversionData: [{ amount: orderTotal, transactionId: orderId }]
});
5. Choose the Right SDK Key Type and Environment
- Use Public keys for client-side JavaScript where the key is visible in the browser.
- Use Authenticated keys only on the server or edge to protect your SDK secret.
- Create separate keys per environment (e.g., Live vs Staging) so you don’t mix experimental data between environments.
6. Use the SDK Config Tab as a Single Source of Truth
- Rely on the SDK Config tab to generate up-to-date sample snippets for your selected SDK and SDK key. This helps keep implementations consistent across services and languages.
Conclusion
These examples demonstrate how to effectively implement Convert's JavaScript SDK for A/B testing and feature flagging.
👉 Ensure proper experiment setup in the Convert dashboard before coding.
👉 Align experiment goals with business objectives.
👉 Follow best practices to ensure reliability and consistency.
👉 Use SDK Config & Keys to manage SDK keys securely and to generate sample code that already includes the correct key and environment configuration for your project.
For more details, visit the official Convert JavaScript SDK documentation. 🚀