Skip to content

@ogygia/flags

Reading flags

Read a flag by calling it with the request, branch with pick, and read a vendor's payload with value(). Flags are read in server code; islands and the browser get the decision as data.

On this page

A flag is a function. You call it with the request, and it returns the decision for that visitor: true or false for a boolean flag, the variant’s name for a weighted one. Branching on several variants, reading a vendor’s payload and stamping the decision into the page are methods on the same function.

import { checkout, hero } from '$lib/flags';
import type { PageServerLoad } from './$types';

export const load: PageServerLoad = (event) => ({
  newCheckout: checkout(event), // boolean
  variant: hero(event), // 'control' | 'bold'
  trialDays: hero.pick(event, { control: 7, bold: 30 }) // 7 | 30
});

Calling a flag

A flag takes a request context: an object with request (a Request), url (a URL), and optionally cookies (with a get(name)) and visitor. Two contexts fit as they are:

  • a SvelteKit RequestEvent, in a server load, a form action, an endpoint or a hook;
  • the server router’s c, in a load, a handler or a when() gate, which also carries c.visitor.

A flag decides once per request. The first read works out the answer and remembers it on that Request, so reading it again in a layout, a page and a component costs nothing and can’t disagree. That first read also does three things you don’t see: it marks the render as belonging to one visitor (Caching), records the decision for federation, and queues one exposure event. Later reads in the same request repeat the mark, and record and send nothing more. Calling the flag, pick and stamp are reads; .value(c) isn’t one yet.

In an endpoint, the event is the context:

import { json } from '@sveltejs/kit';
import { search } from '$lib/flags';
import type { RequestHandler } from './$types';

export const GET: RequestHandler = async (event) => {
  const q = event.url.searchParams.get('q') ?? '';
  const engine =
    search(event) === 'semantic' ? 'vector' : 'keyword';
  return json({ q, engine });
};

pick

pick takes a map from each variant to a thing and gives this visitor their entry. TypeScript requires the map to cover every variant, and the return type is the union of its values. It has two forms.

With the context, flag.pick(c, map) returns the visitor’s value. A boolean flag’s map has off and on:

Without the context, flag.pick(map) returns a page slot for the server router: the router supplies the request when it renders, so each visitor gets their variant’s component. Routing and federation shows it.

pick earns its keep at three or more variants. For a boolean flag you call it, and for two variants a ternary reads as well. If a map lacks the visitor’s variant (a JavaScript caller, a cast), pick falls back to the control’s entry. An entry that is null or undefined counts as missing too, so { control: 'Banner', hidden: null } gives the hidden visitors 'Banner' (#2310). Give a non-control variant a value other than null, such as false or '', or make “nothing” the control.

import { hero, promo } from '$lib/flags';
import type { PageServerLoad } from './$types';

export const load: PageServerLoad = (event) => ({
  label: hero.pick(event, {
    control: 'Buy now',
    bold: 'Get it today'
  }),
  layout: hero.pick(event, {
    control: { columns: 2, video: false },
    bold: { columns: 1, video: true }
  }),
  banner: promo.pick(event, {
    off: null,
    on: 'Summer sale: 20% off'
  })
});

Vendor values

A flag can carry a payload written in the vendor’s dashboard rather than in code, such as a banner’s text. Declare a value schema and a fallback, and .value(c) returns the payload when the source sent a valid one, else the fallback. A payload that fails the schema never gets in, the same trust-boundary rule as a body schema. An async schema counts as failing, since the read is synchronous.

The payload comes from the source, so .value(c) returns something other than the fallback only when a source sends values: ofrep() does whenever the service answers with a non-boolean value, while openfeature() needs values: true (OpenFeature). Without a value schema, .value(c) hands back whatever the source sent, unchecked and typed unknown, or the fallback (else undefined) when it sent nothing. Declare a schema for anything you render.

A vendor can send each visitor a different payload, but .value(c) doesn’t mark the render as belonging to one visitor today: only calling the flag, pick and stamp do (#2310). A page whose only read is .value(c) can be stored by postrender, or cached, with the first visitor’s payload. Until that’s fixed, opt such routes out of postrender with config = { postrender: false } and send Cache-Control: private yourself, since an opted-out route gets none (#2300). Calling the flag in the same load marks the render too. This page does all three. Kit refuses a header set twice, so set cache-control in the page’s own load rather than a layout every page shares:

import { banner } from '$lib/flags';
import type { PageServerLoad } from './$types';

export const config = { postrender: false };

export const load: PageServerLoad = (event) => {
  event.setHeaders({ 'cache-control': 'private, no-store' });
  return {
    show: banner(event), // a read that marks the render per visitor
    banner: banner.value(event) // { text: string; tone: 'info' | 'warn' }
  };
};

Stamps

flag.stamp(c) returns name:variant, such as hero:bold, for a data-og-exp attribute your analytics reads off the page, a log line or a Server-Timing label. Like any read, it decides the flag if nothing has yet.

import { hero } from '$lib/flags';
import type { PageServerLoad } from './$types';

export const load: PageServerLoad = (event) => ({
  stamp: hero.stamp(event)
});
<script lang="ts">
  import type { PageProps } from './$types';

  let { data }: PageProps = $props();
</script>

<section data-og-exp={data.stamp}>…</section>

Where to read

Flags decide on the server, while the request is being answered:

  • Server loads, form actions and endpoints (+page.server.ts, +layout.server.ts, +server.ts), and the server router’s loads, handlers and gates.
  • Hooks, from a handle that runs after ogygia.handle() in sequence(). The source runs inside ogygia.handle(). A read in a handle listed before it decides the flag for the whole request without the source: every later read in that request returns that answer, so a vendor’s kill switch doesn’t apply to it (#2310). Read flags only after ogygia.handle(). The server says flags_source_unprimed only once per process, so later requests show nothing. That message asks you to list the plugin; if flags() is listed, look for a flag read in a handle before ogygia.handle() (#2310).
  • Server-rendered components, through requestEvent() from ogygia, which returns the request’s RequestEvent during a server render and null in the browser. In a server island that’s the island’s own request, so the island decides per visitor even on a stored page (Caching).

Build a server island’s context the same way the page does. The island’s request has no router c.visitor, so passing the raw event keys a signed-in visitor on their og-vid cookie, or on nobody, and they can see one variant in the page and another in the island. Use your own flagContext, as Offer.svelte does below.

Not in universal loads (+page.ts, +layout.ts): they also run in the browser, whose load event has no request, so the types refuse the call. And not in code that runs in the browser, as the next section explains. For an ordinary page, reading the flag in the server load and rendering from data is the simplest.

<script lang="ts">
  import { requestEvent } from 'ogygia';
  import type { RequestEvent } from '@sveltejs/kit';
  import { hero } from '$lib/flags';
  import { flagContext } from '$lib/flag-context';

  const event = requestEvent<RequestEvent>();
  const bold = event
    ? hero(flagContext(event)) === 'bold'
    : false;
</script>

<p class:bold>Save 20% this week</p>

Islands

An island runs in the browser, where a flag can’t decide anything: there’s no request, the og-vid cookie is HttpOnly, and there’s no source and no exposure sink. So decide on the server and hand the island the result as a prop: the variant, a boolean, or what you picked with it. The prop is serialized into the page with the island’s other props, and the island stays as small as it was.

The same goes for a Kit-hydrated page (csr = true): the decision reaches the browser in the server load’s data, and each time Kit runs that load again, it reads the flag for that request.

<script lang="ts">
  import type { PageProps } from './$types';
  import Filters from '$lib/Filters.svelte' with { wake: 'visible' };

  let { data }: PageProps = $props();
</script>

<Filters layout={data.variant === 'bold' ? 'chips' : 'list'} />

Unit tests

A flag needs no server to run. Build a context from a Request, give it a visitor, and call the flag. Outside a server the read can’t mark a render or carry a decision, and the first read on a server-like runtime says flags_plugin_not_running once, which a unit test can ignore.

To test against a source, set it with decide() and run it for your context with prime_flags(c) before the reads, as the plugin does for a real request. await flush_exposures() sends queued exposures to the sink. Outside a request has both.

import { expect, test } from 'vitest';
import { decide } from '@ogygia/flags';
import { hero } from '$lib/flags';

const ctx = (sub: string) => {
  const request = new Request('https://example.com/');
  return {
    request,
    url: new URL(request.url),
    visitor: { sub }
  };
};

test('a visitor keeps their variant', () => {
  expect(hero(ctx('user-1'))).toBe(hero(ctx('user-1')));
});

test('an allowed override picks the variant', () => {
  decide({ overrides: () => true });
  const request = new Request(
    'https://example.com/?og-exp=hero:bold'
  );
  expect(hero({ request, url: new URL(request.url) })).toBe(
    'bold'
  );
});