Agora

Flags 1.x is a release candidate. npm's latest tag still installs 0.x, so install these docs' version from the rc tag:

npm i @adonis-agora/flags@rc
node ace configure @adonis-agora/flags

The same goes for every @adonis-agora/* package these docs install: add @rc, and where a page says node ace add, install with @rc first and then run node ace configure. On 0.x? Read the 0.x docs.

React and Inertia

useFlag, <Flag>, values from your Adonis backend or straight from a flags server, and live updates.

The provider takes flags from one of two places:

valuessource={remoteFlags(...)}
Who evaluatesYour Adonis backend, per requestThe flags server (central server)
ForInertia appsSPAs, mobile, static sites — no Adonis backend of their own
ExperimentsRead the variant in the controllerRendering the flag records the exposure
npm i @adonis-agora/flags-react

Share the values

Only flags declared with client: true are sent — the browser receives values, never targeting rules.

Share them from the Inertia middleware:

app/middleware/inertia_middleware.ts
async share(ctx: HttpContext) {
  return {
    // `await`: all() is async. The `?.` covers pages rendered outside a route (a 404), where the
    // router middleware that sets ctx.flags never ran.
    flags: (await ctx.flags?.all()) ?? {},
  }
}

Then wrap the app in InertiaFlagsProvider. It starts from the first page and follows the flags prop on every Inertia response — visits and reloads:

inertia/app.tsx
import { InertiaFlagsProvider } from '@adonis-agora/flags-react/inertia'

setup({ el, App, props }) {
  createRoot(el).render(
    <InertiaFlagsProvider initialPage={props.initialPage}>
      <App {...props} />
    </InertiaFlagsProvider>,
  )
}

A plain <FlagsProvider values={props.initialPage.props.flags}> there would keep the first page's values: setup runs once.

Read them

import { Flag, useFlag, useFlagEnabled } from '@adonis-agora/flags-react'

function Player() {
  const newPlayer = useFlagEnabled('new_player')
  const maxUploads = useFlag('max_uploads', 10)
  return newPlayer ? <NewPlayer max={maxUploads} /> : <ClassicPlayer />
}

<Flag name="checkout" is="one_page" fallback={<ClassicCheckout />}>
  <OnePageCheckout />
</Flag>

Values are typed from your config/flags.ts. Keys are checked too once you turn on strictKeys (see flags:types); without it any string is accepted, so flags created in the console work before you regenerate types.

Live updates

Values follow every Inertia visit. To change them while the page stays open (a kill switch hiding a banner right away), set realtime: true in config/flags.ts, install @adonisjs/transmit, and hand the provider your Transmit client. It reloads the flags prop whenever the ruleset changes:

inertia/app.tsx
import { transmit } from '~/transmit'

<InertiaFlagsProvider initialPage={props.initialPage} realtime={{ transmit }}>
  <App {...props} />
</InertiaFlagsProvider>

Inertia apps need nothing else: no browser, no token endpoint. Outside the provider, the same thing is a hook:

import { router } from '@inertiajs/react'
import { useFlagsRealtime } from '@adonis-agora/flags-react'

useFlagsRealtime({ transmit, onChange: () => router.reload({ only: ['flags'] }) })

Without Inertia: remoteFlags

For an SPA, a static site or anything that does not render through Inertia, the frontend asks the flags API itself. Turn on browser in config/flags.ts:

config/flags.ts
export default defineConfig({
  flags: { /* … */ },
  browser: {},
})

The flags API authenticates with the token, never with cookies, so @adonisjs/shield's CSRF check must skip it, or it refuses the browser's POSTs:

config/shield.ts
import { flagsCsrfExceptions } from '@adonis-agora/flags'

csrf: {
  enabled: true,
  exceptRoutes: (ctx) => flagsCsrfExceptions(ctx.request.url()),
},
import { FlagsProvider, remoteFlags } from '@adonis-agora/flags-react'

const flags = remoteFlags({ endpoint: '/_flags/token' })

<FlagsProvider source={flags}>
  <App />
</FlagsProvider>

browser mounts GET /_flags/token on your app. It signs the same user ctx.flags uses into a five-minute token and says where the flags API is:

  • with @adonisjs/auth (sessions, access tokens, any guard): ctx.auth.user. Nothing to configure;
  • with @adonis-agora/authkit-client: the authkit identity of the session (sub, email, roles, organization), also with nothing to configure;
  • with your own subject resolver in config/flags.ts: whatever it returns;
  • nobody signed in: an anonymous token, which gets static values only.

The attributes resolver of config/flags.ts runs too, so plan, country and the like travel signed inside the token. With @adonisjs/auth, that is where the user's targeting data comes from:

config/flags.ts
export default defineConfig({
  flags: { /* … */ },
  browser: {},
  attributes: async (subject) => {
    const user = await User.find(subject.id)
    return { plan: user?.plan, country: user?.country }
  },
})

The token is signed, not encrypted: the user can read their own subject and attributes, but cannot change them. The browser holds the token in memory only (never localStorage), fetches a new one shortly before it expires, and retries once with a fresh one if the flags API refuses it.

  1. The browser calls /_flags/token with its session cookie and gets { token, expiresAt, url }.
  2. It calls the flags API at url with the token.

Where the flags API is depends on the topology: on a standalone app it is the app itself; on a tenant, the token points the browser straight at the control-plane. The frontend code is the same either way.

  • Values arrive on mount, refresh every 30 seconds (an unchanged ruleset costs a 304), and change instantly through a server-sent event stream.
  • Until the first answer, hooks return their fallbacks; useFlagsStatus() tells you when values are ready.
  • Rendering an experiment flag (useFlag, useFlagEnabled, <Flag>) records the exposure once per page load. The server re-evaluates the flag, so the browser cannot report a variant it was not assigned.
  • useTrack() records conversions:
const track = useTrack()
<button onClick={() => track('signup_click')}>Sign up</button>

After sign-in or sign-out, call flags.reload(): it drops the token and evaluates for the new user.

The first token in the page

When your Adonis app renders the page that mounts remoteFlags, send the first token with it and skip the first request. browserToken(ctx) signs it like the endpoint does:

app/middleware/inertia_middleware.ts
import { browserToken } from '@adonis-agora/flags'

async share(ctx: HttpContext) {
  return { flagsToken: await browserToken(ctx) }
}
remoteFlags({ endpoint: '/_flags/token', initial: props.initialPage.props.flagsToken })

Keep endpoint: tokens last five minutes, and a page left open needs a new one.

Options

Option
endpointThe token endpoint.
credentials'include' when the frontend is on another origin than the app (also allow it in config/cors.ts). Default 'same-origin'.
initialA token already in the page, to skip the first request: browserToken(ctx) from @adonis-agora/flags.
attributesConveniences (locale, screen). Merged under the token's identity: they cannot change who the user is, and rules on them must never gate access.
pollMs, streamRefresh interval (default 30 s) and the live stream (default on).

Apps that hold their own token

A mobile app or SPA that signs in to authkit itself (PKCE) has an access token and no Adonis session. Give it the flags API URL and the token:

remoteFlags({ url: 'https://flags.example.com/_flags', token: () => auth.accessToken })

and let the flags server accept authkit tokens with browser.verifyUser.

On this page

Partner

Your product as the official integration for Flags, right here.

Become a partner →