Turn a risky feature on only when the flag says exactly true

  • javascript
  • feature-flags
  • security

I have a side project with a paid tier that is built but not open yet. The checkout code is done, the webhook that grants access is done, and there is a small form for people who want to hear when it opens. None of it should be live. I want to merge all of it anyway, so it stops drifting from the main branch, and then open it later by changing one setting.

That plan only works if “off” is really off. A flag that guards something like taking payments or collecting email addresses is not a normal toggle. If it turns on by accident, I charge someone for a thing I am not ready to deliver, or I store personal data I have no page explaining. So I hold these flags to a stricter rule than the cosmetic ones: off unless the value is exactly the string true.

The problem with truthy flags

Environment variables are strings. Every one of them. The most common way I see people read a boolean flag is something like this:

const salesOpen = Boolean(process.env.SALES_OPEN);

That turns on for true, but also for false, 0, no, off, and a single space, because any non-empty string is truthy. Someone sets SALES_OPEN=false to be extra clear that sales are closed, and sales open.

The usual fix is a parser that tries to be helpful:

const salesOpen = ['true', '1', 'yes', 'on'].includes(process.env.SALES_OPEN?.toLowerCase());

This is better, but it still has a wide surface. Now TRUE, Yes, and 1 all open sales, and the next person to edit it might add y or trim whitespace or accept enabled. Each addition is reasonable on its own. Together they mean nobody can say for sure, by reading the dashboard, which values count as on.

For a flag where a false positive costs real money or real trust, I want the opposite trade. A false negative (I set it, typed it wrong, and it stayed off) is annoying for five minutes. A false positive is an incident.

One exact value, checked in one place

So the rule is one comparison:

// flags.js
export function flagOn(name) {
	return process.env[name] === 'true';
}

export const salesOpen = () => flagOn('SALES_OPEN');
export const interestFormOn = () => flagOn('INTEREST_FORM');

Unset is off. Empty is off. false is off. TRUE is off. true with a trailing space is off. Only the four lowercase letters turn it on. That is strict on purpose, and it is easy to explain to anyone, including future me: “it is on when it says true, and nothing else.”

I keep these as functions instead of constants evaluated at import time. On some hosts the module is loaded once and reused, and on others env changes take effect on the next deploy. Reading the value at the moment of the check means there is one answer to “is it on right now,” and tests can set the variable without reloading modules.

Check it where the work happens

The second half of the rule matters as much as the first. The flag has to be checked on the server, at the exact place that does the risky thing, not only in the UI.

Hiding the checkout button when sales are closed is nice, but it is not a control. Anyone can send a request straight to the checkout endpoint. So the endpoint checks the flag itself and refuses:

// POST /api/checkout
export async function POST(request) {
	if (!salesOpen()) {
		return Response.json({ error: 'Sales are not open yet.' }, { status: 503 });
	}
	// create the checkout session...
}

I return a 503 there because the feature exists and is temporarily unavailable, and it tells any client that retrying later is fine. For the interest form, which should not appear to exist at all until it launches, I return a 404 and render nothing on the page:

// POST /api/interest
export async function POST(request) {
	if (!interestFormOn()) return new Response(null, { status: 404 });
	const body = await request.json();
	if (body.consent !== true) {
		return Response.json({ error: 'Consent is required.' }, { status: 400 });
	}
	// record the signup...
}

That last check follows the same idea one level down. The consent checkbox starts unticked, and the server only enrolls someone when the request carries a real boolean true. Not "true", not 1, not “the field was present.” When the value decides whether I store someone’s email, I would rather reject a sloppy client than guess what it meant.

The page uses the same helper, so the UI and the server cannot disagree about whether something is on. If they did disagree, the safe direction is still guaranteed: the button might show and then fail, but the server will never do the thing while the flag is off.

Tradeoffs

This is not how I treat every flag. A flag that swaps a layout or turns on a new chart can be loose, because a mistake there is cosmetic and visible. The strict rule is for flags that guard money, personal data, or anything that sends messages to real people.

Strictness has a cost. Someone will set True in a dashboard, the feature will stay off, and they will lose a few minutes figuring out why. I accept that, and I soften it in two ways. First, I log the parsed state of each risky flag once at startup, so “why is it off” has a one-line answer. Second, I write the accepted value right next to the flag wherever it is documented: “on only when exactly true.”

There is also a temptation to fail loudly on any value that is not true or empty, by throwing at boot. I do not do that for these flags. A typo in a flag should not take the whole site down. It should leave the risky feature off and leave everything else running.

The tests I keep

The helper is tiny, but I still test the values that are most likely to show up by mistake:

import { test } from 'node:test';
import assert from 'node:assert/strict';
import { flagOn } from './flags.js';

for (const value of [undefined, '', 'false', '0', 'TRUE', 'True', 'yes', '1', ' true', 'true ']) {
	test(`flag is off for ${JSON.stringify(value)}`, () => {
		if (value === undefined) delete process.env.X;
		else process.env.X = value;
		assert.equal(flagOn('X'), false);
	});
}

test('flag is on for exactly "true"', () => {
	process.env.X = 'true';
	assert.equal(flagOn('X'), true);
});

Plus one test per guarded endpoint that calls it with the flag off and asserts the 503 or 404. Those are the tests that would catch someone later “simplifying” the check back to a truthy one.

The short version

For a flag that guards something you cannot take back: default off, accept one exact value for on, read it at the moment you need it, and check it on the server where the risky work happens. The UI can hide things, but only the server can refuse them. That lets me merge unfinished paid features weeks early and open them later with one setting I trust.