Feature flags</a> enable a powerful continuous delivery process and provide a platform for <a href=https://www.optimizely.com/"/link/1af76345c9884154a05c52cdb10dbabf.aspx/">progressive delivery</a> with phased rollouts and <a href=https://www.optimizely.com/"/link/26e70699c2f44d17a1ab92863e35503e.aspx/">A/B tests</a>.</p>\n<p>However, feature flags installed in a static site can be difficult because there's usually not a backing database tracking users in a static site.</p>\n<p>In this step-by-step lab, you'll see how to integrate feature flags into a static site with a free version of\nOptimizely, <a href=https://www.optimizely.com/"https://www.optimizely.com/rollouts-signup/?utm_source=labs&amp;utm_campaign=static-site-feature-flags-lab\%22>Optimizely Rollouts</a></p>\n<h2>Pre-requisites</h2>\n<ul>\n<li>A modern web browser</li>\n</ul>\n<h2>Steps</h2>\n<p><em>Note: You can also follow along <a href=https://www.optimizely.com/"https://youtu.be/Q7xjIvQf2G4/">this video</a> with the instructions below</em></p>\n<ol>\n<li>Create an <a href=https://www.optimizely.com/"https://www.optimizely.com/rollouts-signup/?utm_source=labs&amp;utm_campaign=static-site-feature-flags-lab\%22>Optimizely Rollouts Account</a></li>\n<li>Open up a <a href=https://www.optimizely.com/"https://codepen.io/asametrical/pen/PoPPXbQ?editors=1000\%22>blank codepen</a></li>\n<li>Create a static site by pasting in the following html:</li>\n</ol>\n<pre><code>&lt;html&gt;\n &lt;head&gt;\n &lt;/head&gt;\n &lt;body&gt;\n &lt;h1&gt;Hello World&lt;/h1&gt;\n &lt;p id=&quot;subtitle&quot;&gt;This is a subtitle&lt;/p&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n<ol start=\"4\">\n<li>Install the Optimizely SDK via the <a href=https://www.optimizely.com/"https://docs.developers.optimizely.com/rollouts/docs/install-sdk-javascript/">html script tag</a> by placing the below code within the <code>&lt;head&gt;&lt;/head&gt;</code> tags of the html. This makes the SDK available at <code>window.optimizelySdk</code>:</li>\n</ol>\n<pre><code> &lt;script src=https://www.optimizely.com/sv/utvecklare/labs/static-site-feature-flags/&quot;https://unpkg.com/@optimizely/[email protected]/dist/optimizely.browser.umd.min.js&quot;&gt;&lt;/script&gt;/n/n
    html script tag</a> by placing the below code within the <code>&lt;head&gt;&lt;/head&gt;</code> tags of the html. Be sure to replace <code>Your_SDK_Key</code> with your SDK key from the <a href=https://www.optimizely.com/"https://app.optimizely.com/">Optimizely Application</a>. This makes the SDK available at <code>window.optimizelyDatafile</code>:</li>\n</ol>\n<pre><code> &lt;script src=https://www.optimizely.com/sv/utvecklare/labs/static-site-feature-flags/&quot;https://cdn.optimizely.com/datafiles/&lt;Your_SDK_KEY&gt;.json/tag.js&quot;&gt;&lt;/script&gt;/n/n

    You can find your SDK Key in the Optimizely application by navigating to the far left 'Settings' &gt; 'Environments' and copy the Development SDK Key value.</p>\n<p><img src=https://www.optimizely.com/"https://raw.githubusercontent.com/optimizely/labs/master/assets/optimizely-screenshots/sdk-key.gif/" alt=\"Screenshot\" /></p>\n<ol start=\"6\">\n<li>Place the following script tag near the bottom of the html within the <code>&lt;html&gt;</code> tag, which will initialize the SDK:</li>\n</ol>\n<pre><code> &lt;script&gt;\n var optimizelyClientInstance = window.optimizelySdk.createInstance({\n datafile: window.optimizelyDatafile,\n });\n &lt;/script&gt;\n</code></pre>\n<ol start=\"7\">\n<li>Create a feature flag named <code>hello_world</code> in the <a href=https://www.optimizely.com/"https://app.optimizely.com/">Optimizely UI</a>. Navigate to 'Features &gt; Create New Feature' and create a feature flag called 'hello_world':</li>\n</ol>\n<p><img src=https://www.optimizely.com/"https://raw.githubusercontent.com/optimizely/labs/master/assets/optimizely-screenshots/create-flag.gif/" alt=\"Screenshot\" /></p>\n<ol start=\"9\">\n<li>Implement the <code>hello_world</code> feature flag by placing the following code just below our initialization code above:</li>\n</ol>\n<pre><code> var userId = 'user123';\n var enabled = optimizelyClientInstance.isFeatureEnabled('hello_world', userId);\n if (enabled) {\n document.querySelector(&quot;#subtitle&quot;).innerText = &quot;Feature flag is ON!&quot;\n } else {\n document.querySelector(&quot;#subtitle&quot;).innerText = &quot;Feature flag is off&quot;\n }\n</code></pre>\n<ol start=\"9\">\n<li>Define a function to get or generate userIds and replace <code>user123</code> with <code>getOrGenerateUserId()</code>:</li>\n</ol>\n<pre><code> function getOrGenerateUserId() {\n var userId;\n try {\n var storageKey = 'optimizely-userId'\n userId = window.localStorage.getItem(storageKey);\n if (!userId) {\n userId = String(Math.random());\n localStorage.setItem(storageKey, userId);\n }\n } catch {\n console.warn('[OPTIMIZELY] LocalStorage not available to store userId. Generating random userId each page load');\n userId = String(Math.random());\n }\n return userId;\n }\n\n var userId = getOrGenerateUserId();\n</code></pre>\n<ol start=\"10\">\n<li>Now you can turn the feature flag on and off in the Optimizely UI and see the changes in your static site! 🎉</li>\n</ol>\n<p>To turn on your feature flag:</p>\n<ol>\n<li>Navigate to Features</li>\n<li>Click on the 'hello_world' feature</li>\n<li>Change to the 'Development' environment to match the SDK Key we used</li>\n<li>Roll the feature out to ensure it is set to 100% for everyone</li>\n<li>Click Save to save your changes</li>\n</ol>\n<p><img src=https://www.optimizely.com/"https://raw.githubusercontent.com/optimizely/labs/master/assets/optimizely-screenshots/flag-rollout-dev.gif/" alt=\"Screenshot\" /></p>\n<p>After at least 10 seconds you can try and reload the codepen page to see the feature flag update has propagated to your application.</p>\n<p>If you did not see the feature flag turn on, double check that you are not running any ad-blockers and check your code against a full code sample below (being sure to update the SDK key to your own SDK key):</p>\n<pre><code>&lt;html&gt;\n &lt;head&gt;\n &lt;script src=https://www.optimizely.com/sv/utvecklare/labs/static-site-feature-flags/&quot;https://unpkg.com/@optimizely/[email protected]/dist/optimizely.browser.umd.min.js&quot;&gt;&lt;/script&gt;/n &lt;script src=https://www.optimizely.com/sv/utvecklare/labs/static-site-feature-flags/&quot;https://cdn.optimizely.com/datafiles/V7kE2tbrJaYGmtRF5W5QXf.json/tag.js&quot;&gt;&lt;/script&gt;/n &lt;/head&gt;\n &lt;body&gt;\n &lt;h1&gt;Hello World&lt;/h1&gt;\n &lt;p id=&quot;subtitle&quot;&gt;This is a subtitle&lt;/p&gt;\n &lt;/body&gt;\n &lt;script&gt;\n var optimizely = optimizelySdk.createInstance({\n datafile: window.optimizelyDatafile,\n });\n\n function getOrGenerateUserId() {\n var userId;\n try {\n var storageKey = 'optimizely-userId'\n userId = window.localStorage.getItem(storageKey);\n if (!userId) {\n userId = String(Math.random());\n localStorage.setItem(storageKey, userId);\n }\n } catch {\n console.warn('[OPTIMIZELY] LocalStorage not available to store userId. Generating random userId each page load');\n userId = String(Math.random());\n }\n return userId;\n }\n\n var userId = getOrGenerateUserId();\n var enabled = optimizelyClientInstance.isFeatureEnabled('hello_world', userId);\n if (enabled) {\n document.querySelector(&quot;#subtitle&quot;).innerText = &quot;Feature flag is ON!&quot;\n } else {\n document.querySelector(&quot;#subtitle&quot;).innerText = &quot;Feature flag is off&quot;\n }\n &lt;/script&gt;\n&lt;/html&gt;\n</code></pre>\n","labels":"full stack, static site, feature flags","revisionDate":"2020-07-13","resourceFile":null,"resourceFileName":null,"author":null,"repositoryUrl":"https://raw.githubusercontent.com/optimizely/labs/master/labs/static-site-feature-flags/README.md","labelsLabel":"Labels","publishedLabel":"Published","resourcesLabel":"Resources","repositoryLabel":"Repository","authorLabel":"Author"}" data-redux="false" data-router="false">

    Static Site Feature Flags

    Note: Turn off any ad-blockers! Ad-blockers can prevent this demo from working.

    Feature flags enable a powerful continuous delivery process and provide a platform for progressive delivery with phased rollouts and A/B tests.

    However, feature flags installed in a static site can be difficult because there's usually not a backing database tracking users in a static site.

    In this step-by-step lab, you'll see how to integrate feature flags into a static site with a free version of Optimizely, Optimizely Rollouts

    Pre-requisites

    • A modern web browser

    Steps

    Note: You can also follow along this video with the instructions below

    1. Create an Optimizely Rollouts Account
    2. Open up a blank codepen
    3. Create a static site by pasting in the following html:
    <html>
      <head>
      </head>
      <body>
        <h1>Hello World</h1>
        <p id="subtitle">This is a subtitle</p>
      </body>
    </html>
    
    1. Install the Optimizely SDK via the html script tag by placing the below code within the <head></head> tags of the html. This makes the SDK available at window.optimizelySdk:
        <script src="https://unpkg.com/@optimizely/[email protected]/dist/optimizely.browser.umd.min.js"></script>
    
    1. Install the datafile for your project using the html script tag by placing the below code within the <head></head> tags of the html. Be sure to replace Your_SDK_Key with your SDK key from the Optimizely Application. This makes the SDK available at window.optimizelyDatafile:
        <script src="https://cdn.optimizely.com/datafiles/<Your_SDK_KEY>.json/tag.js"></script>
    

    You can find your SDK Key in the Optimizely application by navigating to the far left 'Settings' > 'Environments' and copy the Development SDK Key value.

    Screenshot

    1. Place the following script tag near the bottom of the html within the <html> tag, which will initialize the SDK:
      <script>
        var optimizelyClientInstance = window.optimizelySdk.createInstance({
          datafile: window.optimizelyDatafile,
        });
      </script>
    
    1. Create a feature flag named hello_world in the Optimizely UI. Navigate to 'Features > Create New Feature' and create a feature flag called 'hello_world':

    Screenshot

    1. Implement the hello_world feature flag by placing the following code just below our initialization code above:
        var userId = 'user123';
        var enabled = optimizelyClientInstance.isFeatureEnabled('hello_world', userId);
        if (enabled) {
          document.querySelector("#subtitle").innerText = "Feature flag is ON!"
        } else {
          document.querySelector("#subtitle").innerText = "Feature flag is off"
        }
    
    1. Define a function to get or generate userIds and replace user123 with getOrGenerateUserId():
        function getOrGenerateUserId() {
          var userId;
          try {
            var storageKey = 'optimizely-userId'
            userId = window.localStorage.getItem(storageKey);
            if (!userId) {
              userId = String(Math.random());
              localStorage.setItem(storageKey, userId);
            }
          } catch {
            console.warn('[OPTIMIZELY] LocalStorage not available to store userId. Generating random userId each page load');
            userId = String(Math.random());
          }
          return userId;
        }
    
        var userId = getOrGenerateUserId();
    
    1. Now you can turn the feature flag on and off in the Optimizely UI and see the changes in your static site! 🎉

    To turn on your feature flag:

    1. Navigate to Features
    2. Click on the 'hello_world' feature
    3. Change to the 'Development' environment to match the SDK Key we used
    4. Roll the feature out to ensure it is set to 100% for everyone
    5. Click Save to save your changes

    Screenshot

    After at least 10 seconds you can try and reload the codepen page to see the feature flag update has propagated to your application.

    If you did not see the feature flag turn on, double check that you are not running any ad-blockers and check your code against a full code sample below (being sure to update the SDK key to your own SDK key):

    <html>
      <head>
        <script src="https://unpkg.com/@optimizely/[email protected]/dist/optimizely.browser.umd.min.js"></script>
        <script src="https://cdn.optimizely.com/datafiles/V7kE2tbrJaYGmtRF5W5QXf.json/tag.js"></script>
      </head>
      <body>
        <h1>Hello World</h1>
        <p id="subtitle">This is a subtitle</p>
      </body>
      <script>
        var optimizely = optimizelySdk.createInstance({
          datafile: window.optimizelyDatafile,
        });
    
        function getOrGenerateUserId() {
          var userId;
          try {
            var storageKey = 'optimizely-userId'
            userId = window.localStorage.getItem(storageKey);
            if (!userId) {
              userId = String(Math.random());
              localStorage.setItem(storageKey, userId);
            }
          } catch {
            console.warn('[OPTIMIZELY] LocalStorage not available to store userId. Generating random userId each page load');
            userId = String(Math.random());
          }
          return userId;
        }
    
        var userId = getOrGenerateUserId();
        var enabled = optimizelyClientInstance.isFeatureEnabled('hello_world', userId);
        if (enabled) {
          document.querySelector("#subtitle").innerText = "Feature flag is ON!"
        } else {
          document.querySelector("#subtitle").innerText = "Feature flag is off"
        }
      </script>
    </html>
    
    Additional links