@rsc-kit/mcp
Version:
An MCP server over what an rsc-kit build decided: the routes, why each one is static or not, and what it costs the browser.
232 lines (177 loc) • 7.41 kB
Markdown
# Feature flags
> OpenFeature in a server component, Pennant on Laravel, the OpenFeature Go SDK on Go.
Read a flag in a server component and render from it. In a JavaScript app, use
[OpenFeature](https://openfeature.dev), the vendor-neutral flag standard. It
runs the same on Bun, Node and Workers, and the service that holds your flags
plugs in as a provider. With a backend, use the backend's own: Laravel
[Pennant](#laravel-pennant), or [OpenFeature's Go SDK](#go).
```sh
bun add /server-sdk @openfeature/core
```
```ts title="src/server/flags.ts"
import { cache } from 'react'
import { OpenFeature, InMemoryProvider } from '/server-sdk'
await OpenFeature.setProviderAndWait(
new InMemoryProvider({
'new-banner': {
variants: { on: true, off: false },
defaultVariant: 'off',
disabled: false,
},
}),
)
const client = OpenFeature.getClient()
export const newBanner = cache(() => client.getBooleanValue('new-banner', false))
```
```tsx title="src/app/page.tsx"
import { newBanner } from '../server/flags'
export default async function Home() {
return (await newBanner()) ? <Banner /> : null
}
```
React's `cache()` evaluates a flag once per render, however many components
ask for it. A flag that is the same for everyone doesn't read the request, so
the page is stored at build like any other.
## Deciding per visitor
A flag usually depends on who is asking. Build OpenFeature's evaluation context
from the request, and pass it with every evaluation:
```ts title="src/server/flags.ts"
import { cache } from 'react'
import { OpenFeature, InMemoryProvider } from '/server-sdk'
import { cookies } from '-kit/core/request'
await OpenFeature.setProviderAndWait(
new InMemoryProvider({
'new-banner': {
variants: { on: true, off: false },
defaultVariant: 'off',
disabled: false,
contextEvaluator: (context) => (context.targetingKey === 'ada' ? 'on' : 'off'),
},
}),
)
const client = OpenFeature.getClient()
const visitor = cache(async () => ({
targetingKey: (await cookies()).get('user')?.value ?? 'anonymous',
}))
export const newBanner = cache(async () => client.getBooleanValue('new-banner', false, await visitor()))
```
`targetingKey` is who the flag is decided for, usually a user id. Any other
field you add is an attribute the provider can target on, such as a country or
a plan.
A flag that reads the visitor makes what renders it per visitor. Put that part
under `<Suspense>`, so the rest of the page is still stored as a shell:
```tsx title="src/app/page.tsx"
import { Suspense } from 'react'
import { newBanner } from '../server/flags'
async function Banner() {
return (await newBanner()) ? <p>Try the new board</p> : null
}
export default function Home() {
return (
<main>
<h1>Tasks</h1>
<Suspense fallback={null}>
<Banner />
</Suspense>
</main>
)
}
```
Without the boundary the read is above everything, and the whole page renders
per request.
## Using a flag service
`InMemoryProvider` holds the flags in code, which is enough to ship a feature
behind a switch. To change flags without a deploy, swap it for the provider of
the service that holds them. OpenFeature lists them in its
[ecosystem](https://openfeature.dev/ecosystem). The evaluation calls don't
change:
```ts
await OpenFeature.setProviderAndWait(new YourServiceProvider({ /* its options */ }))
```
`setProviderAndWait` runs once, when the server starts, and rejects if the
provider can't start, so the server doesn't come up without its flags. Use
`setProvider` instead to start without waiting: until the provider is ready,
and whenever an evaluation fails, a flag answers the default you passed. An
evaluation never throws, so a page never fails over a flag.
## Laravel: Pennant
On Laravel, flags are [Pennant](https://laravel.com/docs/pennant), defined as
Pennant's docs show. A page reads one through a class under `app/Rsc`:
```php title="app/Providers/AppServiceProvider.php"
use App\Models\User;
use Laravel\Pennant\Feature;
public function boot(): void
{
Feature::define('new-banner', fn (User $user) => $user->isInternal());
}
```
```php title="app/Rsc/Flags.php"
namespace App\Rsc;
use Laravel\Pennant\Feature;
class Flags
{
public function newBanner(): bool
{
return Feature::active('new-banner');
}
}
```
```tsx title="resources/js/app/page.tsx"
async function Banner() {
return (await rpc('Flags.newBanner')) ? <p>Try the new board</p> : null
}
```
Pennant decides a flag for the signed-in user by default, and the call has the
visitor's session, so `Feature::active()` is decided for them. The build sees
that read and leaves the call to the request, so put the component under
`<Suspense>` as above. A flag decided for nobody, `Feature::for(null)`, is
answered once at build and stored with the page.
To share one flag service between Laravel and a JavaScript app, OpenFeature has
a [PHP SDK](https://openfeature.dev/docs/reference/technologies/server/php) with
the same providers.
## Go
On Go, use [OpenFeature's Go SDK](https://openfeature.dev/docs/reference/technologies/server/go)
in a handler. Pass the handler's `ctx`, and build the evaluation context from the
visitor:
```go title="flags.go"
client := openfeature.NewDefaultClient()
reg.Handle("Flags.newBanner", func(ctx context.Context) (bool, error) {
visitor := openfeature.NewEvaluationContext(userID(rsckit.HeadersFrom(ctx)), nil)
return client.BooleanValue(ctx, "new-banner", false, visitor)
})
```
```tsx title="src/app/page.tsx"
async function Banner() {
return (await rpc('Flags.newBanner')) ? <p>Try the new board</p> : null
}
```
The build sees `HeadersFrom` and leaves the call to the request. It also sees
the SDK look up its own context value, which it can't tell apart from a visitor
read, so even a flag that is the same for everyone isn't stored. If your app
never sets OpenFeature's transaction context, tell the build that value isn't
the visitor:
```go
reg.ServeCalls(os.Stdin, os.Stdout, rsckit.NotTheVisitor("github.com/open-feature/go-sdk/openfeature"))
```
A flag read with the headers still streams per visitor; one that is the same
for everyone is then stored. See
[Reading from Go](/hosts/go/reading-from-go) for what else the build watches.
## Testing a flag
A flag that reads the request evaluates in a test inside `withRequest()`:
```ts title="tests/flags.test.ts"
import { expect, test } from 'bun:test'
import { withRequest } from '-kit/core/request'
import { newBanner } from '../src/server/flags'
test('the banner is on for ada only', async () => {
const as = (cookie: string) => new Request('https://app.test/', { headers: { Cookie: cookie } })
expect(await withRequest(as('user=ada'), newBanner)).toBe(true)
expect(await withRequest(as('user=grace'), newBanner)).toBe(false)
})
```
On Laravel, test the flag with Pennant's own `Feature::activate()` and
`Feature::deactivate()`, as in any Laravel test.
## Why not a framework's flag SDK
A flag SDK built for one framework reads the request through that framework,
and rsc-kit would have to impersonate it. The integration then breaks whenever
the SDK reaches for something new: Vercel's `flags/next` started importing
`next/navigation` in 4.5.2. OpenFeature takes the request as data you pass in,
so there is nothing to impersonate.