Reading a Feature Flag in the Browser

How your page's own JavaScript asks whether a code flag is on, reads its payload, and sets the attributes rings can match, plus the cases where a flag reads Off.

2 min read


A code flag can be read by the page's own JavaScript once the Pertento snippet has loaded. There is nothing to install beyond the snippet itself. See Installing the Pertento script.

Ask for the flag

// Once the Pertento snippet has loaded:
if (window.Pertento.isOn('new-checkout')) {
  // On: the new path.
}

const { on, payload } = window.Pertento.flag('new-checkout');
// payload: the side's JSON, if the flag has one

isOn(key) answers true or false. flag(key) answers an object with on and the side's payload. The flag's Setup tab shows both, filled in with the flag's key.

An unknown key answers Off. So does a page outside the flag's targeting. Every website's script answers isOn and flag, including a website with no live flags, and an archived flag answers Off, so code that still reads a flag you have retired does not break.

The snippet loads asynchronously

Before the snippet has run, window.Pertento does not exist and a call throws. Read flags after the snippet has loaded, or guard the call:

if (window.Pertento?.isOn?.('new-checkout') === true) {
  // On
}

The guard reads Off until the snippet is ready, which is the right default for a release.

Attributes for rings

If the flag has rings with attribute rules, set the facts they match before the Pertento snippet:

// Before the Pertento snippet: facts your rings can match.
window.PertentoAttributes = { staff: false, plan: 'pro' };

See Who Gets a Feature Flag for how rings are matched.

What else decides the answer

  • The rollout. A visitor outside the rollout gets Off, and a code flag published without a rollout is at 0%.
  • Targeting. In the browser, the flag is Off on pages the targeting rules do not match.
  • Rings. A ring that serves Off wins over the rollout.
  • Storage. A visitor's side is kept in the browser's storage. If storage is blocked, a flag between 0% and 100% can change side between page loads.
  • A customer ID flag. A flag that buckets on Customer ID can only be read in the browser when your server seeded the page with its decision. Otherwise it reads Off. See Reading a Feature Flag on Your Server.

If a flag reads Off when you expect On, go through Why Does My Feature Flag Read Off?.