https://www.growthbook.io/ logo
Join Slack
Powered by
# sdk-javascript
  • b

    brief-honey-45610

    09/21/2023, 4:03 AM
    set the channel topic: Ask questions here related to the JavaScript SDK.
  • b

    brief-honey-45610

    09/21/2023, 4:03 AM
    set the channel description: Ask questions here related to the JavaScript SDK.
  • f

    famous-bird-26809

    12/12/2023, 8:40 PM
    Hello, I'm currently implementing Vue.js SDK with composition API in our Nuxt SPA application. Feature flags works fine, I'm able to fetch them. When it comes to Visual editor it seems like I can't see changes done in expirement so probably I missed something. Before my implementation, we have had growthbook implemented by GTM described in this doc: https://docs.growthbook.io/guide/google-tag-manager-and-growthbook. In this case expirements created with Visual editor works well. My question is: Is it possible to use Visual editor in expirements in SPA application using only Vue SDK? Why feature flags works well, while I cant see eny expirements in response configured in panel? Unfortunately visual editor is very important tool for my organization so Im wondering if we really should implement it in our codebase or leave it in gtm? Appreciate any advices, thanks
    b
    • 2
    • 1
  • b

    busy-air-96466

    01/02/2024, 3:52 PM
    Hiya, is there an obvious reason why the GrowthBook devtools extension for Chrome wouldn't work on a test network? Everything else in GrowthBook seems to be working perfectly. I can see from the network tab that the SDK is present and finding an active experiment. The "collect" events such as "experiment_viewed" are being sent, and the experiment UX is visible. On my localhost, the devtools are finding the SDK, but on the remote Test environment, devtools is failing to connect. Adblocker is disabled; VPN is disabled. I can see from the console that enableDevMode is true I've unstalled and reinstalled the extension: closed and reopened Chrome; cleared the cache. Devtools worked on the network version of the app back in 2023...just wondering if I'm missing something obvious? Thank you!
  • p

    plain-judge-50181

    02/08/2024, 7:56 AM
    Hi Team, I am trying to integrate Growthbook in my code. So I have done a small POC on it. But I don't see the features (Getting undefined) Could anyone please help, If I am making any mistake? Thanks you Code is here
    Copy code
    const { GrowthBook, setPolyfills } = require('@growthbook/growthbook');
    
    
    setPolyfills({
      // Required when using built-in feature loading and Node 17 or lower
      fetch: require("cross-fetch"),
      // Required when using encrypted feature flags and Node 18 or lower
      SubtleCrypto: require("node:crypto").webcrypto.subtle,
      // Optional, can make feature rollouts faster
      EventSource: require("eventsource"),
      // Optional, can reduce startup times by persisting cached feature flags
      localStorage: {
        // Example using Redis
        getItem: (key) => redisClient.get(key),
        setItem: (key, value) => redisClient.set(key, value),
      }
    })
    
    const initGrwothBook = async () => {
        return new GrowthBook({
            apiHost: "hmyhost",
            clientKey: "sdk-key",
            // Enable easier debugging during development
            enableDevMode: true,
            // Update the instance in realtime as features change in GrowthBook
            subscribeToChanges: true,
            // Targeting attributes
            attributes: {
                id: "123",
                country: "US"
            },
            // Only required for A/B testing
            // Called every time a user is put into an experiment
            trackingCallback: (experiment, result) => {
                console.log("Experiment Viewed", {
                    experimentId: experiment.key,
                    variationId: result.key,
                });
            },
        });
    }
    
    async function init() {
        // Wait for features to be available
        const gb = await initGrwothBook();
        // console.log(gb);
        try{
           const features = await gb.loadFeatures();
           console.log('Grwothbook features ', features); // getting undefined
        }catch(err){
            console.log('Error GrwothBook features ', err);
        }
    }
    init();
  • h

    hundreds-agent-51861

    02/22/2024, 11:03 AM
    https://growthbookusers.slack.com/archives/C01T6Q1SVFV/p1708090102857979 I have been facing this issue on production. Could anyone respond on this?
  • f

    fresh-helicopter-69423

    02/28/2024, 11:20 AM
    Hi everyone I have been facing an issue and reaching out for help Issue: On updating a feature flag value, getting those values after couple of app session Details: I'm using the feature flag feature of GB in a react native application Currently I don't want to auto refresh the features in a single app session, so while initialising the sdk, I'm passing auto refresh as false and because of that no subscribedInstances are created. The issue is that when I fetch feature,
    onNewFeatureData
    is called and it sets the newly fetched features only when you have any
    subscribedInstances
    . Since I don't have any subscribed instances, the values are not set in the same app session but only updates the cache.
    Copy code
    function onNewFeatureData(
      key: string,
      cacheKey: string,
      data: FeatureApiResponse
    ): void {
      ......
      updatePersistentCache();
    
      // Update features for all subscribed GrowthBook instances
      const instances = subscribedInstances.get(key);
      instances && instances.forEach((instance) => refreshInstance(instance, data));
    }
    Solution: a straight forward solution for my usecase will be to replace the instance check with the below code as my app does not support auto refresh feature
    Copy code
    instance && data && setFeaturesOnInstance(instance, data)
    I wanted the understand the implications of these changes and is there any other way to solve this issue TIA!
  • m

    magnificent-magician-7659

    05/09/2024, 3:03 PM
    👋 Hello, team! Can I get help on Node.js implementation error here? Issue:
    import { GrowthBook } from "@growthbook/growthbook";
    ^^^^^^^^^^
    SyntaxError: Named export 'GrowthBook' not found. The requested module '@growthbook/growthbook' is a CommonJS module, which may not support all module.exports as named exports.
    I’m following std SDK implementation manual for Node.js (v20)
  • o

    orange-manchester-61441

    05/14/2024, 10:37 AM
    Hey all, I have a strange caching problem with the SDK version
    0.26.0
    . As I understand that there are two level of cache in-memory and local-storage. What I am seeing is sometimes the cache returns really older version of the data and cache in local-storage is not updated. Has anyone seen this issue? I can just turn off the cache in the config but I want to understand why it would return old version of the data.
  • f

    flat-advantage-68891

    08/21/2024, 12:09 PM
    I am looking for guidance in terms of what the best approach is for implementing unit tests with the latest SDKs. In general it seems there needs to be support for the following. • a flag or something to enable a local mode during initialization (where it doesn't go out over the network) • a way to explicitly override a specific feature flag with a unit test (used during the setting up initial state portion of the test) • a way to clear all feature flag overrides (used in a hook before each test case to make sure we don't have state bleeding across tests) I am particularly interested in the Javascript, Ruby, and Flutter SDKs. Reading through the Javascript docs, https://docs.growthbook.io/lib/js, I don't see anything that would address the above needed functionality. How are people writing test cases for the on & off cases when a feature toggle is in play. Please provide any information or guidance.
  • b

    billowy-lizard-55653

    11/19/2024, 1:37 PM
    Hi folks. I have a query about the GTM implementation of GB, I have followed the tutorial for this in the docs. It looks like the experiment_viewed event is appearing twice in the data layer and being fired to GA4 twice. As per the instructions I have a Custom HTML tag to load the GB SDK, and a GA4 Event tag for the experiment_viewed event. Any ideas why this is happening/if it is expected behaviour? Data layer debug:
    Copy code
    5: {
    0: "event"
    1: "experiment_viewed"
    2: {
    experiment_id: "test-feature"
    variation_id: "0"
    }
    }
    6: {
    event: "experiment_viewed"
    experiment_id: "test-feature"
    gtm.uniqueEventId: 15
    variation_id: "0"
    }
    d
    • 2
    • 2
  • d

    dry-market-38093

    11/28/2024, 3:07 PM
    Hello everyone, how are you? I need help with an click event... I included an HTML modal and need to control its closing and save a variable on localstorage so it doesn't show again after user interaction. I created the code and tested on Codepen and works fine, but when I try on growthbook nothing happens... any ideas? Here is the code:
    Copy code
    document.addEventListener("DOMContentLoaded", function () {
      // Verifica se a modal já foi exibida
      if (!localStorage.getItem("paymentModalShown")) {
        showModal();
      }
    
      // Função para exibir a modal
      function showModal() {
        const modal = document.getElementById("paymentModal");
        modal.style.display = "flex";
        localStorage.setItem("paymentModalShown", "true"); // Salva no localStorage
      }
    
      // Fecha a modal quando o "X" é clicado ou quando a área fora da modal é clicada
      const closeButton = document.querySelector(".close-btn");
      const modal = document.getElementById("paymentModal");
    
      closeButton.addEventListener("click", closeModal);
      modal.addEventListener("click", function (event) {
        if (event.target === modal) {
          closeModal();
        }
      });
    
      // Função para fechar a modal
      function closeModal() {
        const modal = document.getElementById("paymentModal");
        localStorage.setItem("paymentModalShown", "true"); // Salva no localStorage
        modal.style.display = "none";
      }
    });
  • e

    enough-ice-36370

    12/05/2024, 3:05 PM
    Hi, I am trying to create a simple UI in our Expo React Native app written in Typescript that is only available in dev-mode that would allow the devs to force a specific variation for any experiment that we have defined in GrowthBook. The plan was to make use of the
    setForcedVariations
    method in the
    GrowthBook
    class. Is there some way to get hold of the list of these GrowthBook experiments? I tried calling the
    getExperiments()
    method but that always returns an empty array - I am assuming that this would just return the experiments that may have been passed in via the constructor which is not what I want.
  • b

    bland-jewelry-79981

    03/03/2025, 6:00 PM
    Hi, I've enabled sticky bucket, configured an alternative attribute in the experiment (
    userId
    primary,
    anonymousId
    alternative), I enter the site in anonymous I get variation A, I login and I still get variation A, even if
    userId
    hash would end up choosing variation B, and that's fine but now I change device, I login and I'm on variation B, and at this point I was expecting variation A as the official documentation says:
    The very first variation a user is assigned to will "stick" to them and follow them across devices. So if a visitor lands on your website, gets assigned variation B (from their fallback attribute), and then logs in, they will continue seeing variation B, even though they now have a
    userId
    attribute. If that same user then logs into your app on a new device, they again will continue seeing variation B.
    what I'm missing?
    s
    • 2
    • 6
  • n

    narrow-toddler-83757

    06/07/2025, 4:03 AM
    Hey y'all I'm trying to use the SDK in an express app, and I keep getting a
    ReferenceError: MutationObserver is not defined
    when I try to instantiate a GrowthbookClient instance. Feels strange that we need a mutationObserver for a backend SDK -- is there something obvious here I'm missing?
    s
    • 2
    • 7
  • c

    curved-machine-78995

    07/15/2025, 7:02 AM
    Hey all, I'm trying to access the features I have created in GB. But I'm facing an issue - getting an error -
    Application error: a client-side exception has occurred (see the browser console for more information).
    when I try to click on any of the features. I am getting the same error when I click on web hooks under the settings section. Can someone help me on this ?
    s
    • 2
    • 6