Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add support for building Next.JS apps that use suspending flags. #1157

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 16 additions & 9 deletions packages/react/src/evaluation/use-feature-flag.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,24 @@ import type {
EventHandler,
FlagEvaluationOptions,
FlagValue,
JsonValue} from '@openfeature/web-sdk';
import {
ProviderEvents,
ProviderStatus,
JsonValue,
} from '@openfeature/web-sdk';
import { ProviderEvents, ProviderStatus } from '@openfeature/web-sdk';
import { useEffect, useRef, useState } from 'react';
import {
DEFAULT_OPTIONS,
isEqual,
normalizeOptions,
suspendUntilInitialized,
suspendUntilReconciled,
useProviderOptions,
} from '../internal';
import type { ReactFlagEvaluationNoSuspenseOptions, ReactFlagEvaluationOptions } from '../options';
import { DEFAULT_OPTIONS, isEqual, normalizeOptions, suspendUntilReady, useProviderOptions } from '../internal';
import { useOpenFeatureClient } from '../provider/use-open-feature-client';
import { useOpenFeatureClientStatus } from '../provider/use-open-feature-client-status';
import { useOpenFeatureProvider } from '../provider/use-open-feature-provider';
import type { FlagQuery } from '../query';
import { HookFlagQuery } from './hook-flag-query';
import { HookFlagQuery } from '../internal/hook-flag-query';

// This type is a bit wild-looking, but I think we need it.
// We have to use the conditional, because otherwise useFlag('key', false) would return false, not boolean (too constrained).
Expand Down Expand Up @@ -280,15 +286,16 @@ function attachHandlersAndResolve<T extends FlagValue>(
const defaultedOptions = { ...DEFAULT_OPTIONS, ...useProviderOptions(), ...normalizeOptions(options) };
const client = useOpenFeatureClient();
const status = useOpenFeatureClientStatus();
const provider = useOpenFeatureProvider();

const controller = new AbortController();

// suspense
if (defaultedOptions.suspendUntilReady && status === ProviderStatus.NOT_READY) {
suspendUntilReady(client);
suspendUntilInitialized(provider, client);
}

if (defaultedOptions.suspendWhileReconciling && status === ProviderStatus.RECONCILING) {
suspendUntilReady(client);
suspendUntilReconciled(client);
}

const [evaluationDetails, setEvaluationDetails] = useState<EvaluationDetails<T>>(
Expand Down
6 changes: 4 additions & 2 deletions packages/react/src/internal/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ import { normalizeOptions } from '.';

/**
* The underlying React context.
* DO NOT EXPORT PUBLICLY
*
* **DO NOT EXPORT PUBLICLY**
* @internal
*/
export const Context = React.createContext<
Expand All @@ -14,7 +15,8 @@ export const Context = React.createContext<

/**
* Get a normalized copy of the options used for this OpenFeatureProvider, see {@link normalizeOptions}.
* DO NOT EXPORT PUBLICLY
*
* **DO NOT EXPORT PUBLICLY**
* @internal
* @returns {NormalizedOptions} normalized options the defaulted options, not defaulted or normalized.
*/
Expand Down
11 changes: 11 additions & 0 deletions packages/react/src/internal/errors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@


const context = 'Components using OpenFeature must be wrapped with an <OpenFeatureProvider>.';
const tip = 'If you are seeing this in a test, see: https://openfeature.dev/docs/reference/technologies/client/web/react#testing';

export class MissingContextError extends Error {
constructor(reason: string) {
super(`${reason}: ${context} ${tip}`);
this.name = 'MissingContextError';
}
}
68 changes: 52 additions & 16 deletions packages/react/src/internal/suspense.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,57 @@
import type { Client} from '@openfeature/web-sdk';
import { ProviderEvents } from '@openfeature/web-sdk';
import type { Client, Provider } from '@openfeature/web-sdk';
import { NOOP_PROVIDER, ProviderEvents } from '@openfeature/web-sdk';
import { use } from './use';

/**
* A weak map is used to store the global suspense status for each provider. It's
* important for this to be global to avoid rerender loops. Using useRef won't
* work because the value isn't preserved when a promise is thrown in a component,
* which is how suspense operates.
*/
const globalProviderSuspenseStatus = new WeakMap<Provider, Promise<unknown>>();
Copy link
Member

@lukas-reining lukas-reining Feb 27, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not 100% sure but globals in Next.js code tend to create weird states.
If this code is run on the server globalProviderSuspenseStatus will be the same for every caller if I recall correctly.
This means when we save a provider here I think we could either get multiple instances of the provider, or the same provider with the same eval context on multiple clients.

But I might be overseeing anything here that avoids this.

This is what I am not sure about if it applies here: vercel/next.js#47605

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's worth noting that Vercel's SWR library also maintains a global state using a weakmap.

https://github.com/vercel/swr/blob/975f99118fc11eedc79accceb6eeaead19753db9/src/_internal/utils/global-state.ts

In our case, the weakmap is useful for handling the noop provider and some minor initialization optimizations. I don't think it would be a big deal if we lose state between requests. Basically, it would behave how it current done.

Copy link
Member

@lukas-reining lukas-reining Feb 27, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the problem would be more that we might confuse providers.

From the Issue:

Since mutating server-side global variables does some combination of a) not updating when you expect them to b) resetting arbitrarily c) leaking memory and d) leaking user data,

E.g. look at TanStack Query: https://tanstack.com/query/latest/docs/framework/react/guides/ssr?from=reactQueryV3#initial-setup
They say:

// NEVER DO THIS:
// const queryClient = new QueryClient()
//
// Creating the queryClient at the file root level makes the cache shared
// between all requests and means all data gets passed to all users.
// Besides being bad for performance, this also leaks any sensitive data.

Copy link
Member

@lukas-reining lukas-reining Feb 27, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I imagine that when we have a static context provider in this list, this could become a problem here.
Maybe we have that problem already between different users with our singleton API, which does not have it's roots in this PR 🤔

Copy link
Member

@lukas-reining lukas-reining Feb 27, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looking at swr, I see that the WeakMap maps a cache object to a specific cache state.
For me it is not entirely clear if the provider stored in our case is unique for the user or even the request.

I think OpenFeature.setProvider could be a problem in the React SDK when used with Next.js.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You may be right and perhaps I should update the PR title to not include Next.JS. This PR definitely addresses a build-time issue that's easily reproducible with Next. However, as you stated, we'll likely need to do more to properly support Next.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This PR definitely addresses a build-time issue that's easily reproducible with Next.

Totally!

You may be right and perhaps I should update the PR title to not include Next.JS
Removing Next from the title would make sense to me.

The problem is that running Next with the React SDK currently can lead to security problems if I understand correctly.


/**
* Suspends until the client is ready to evaluate feature flags.
* DO NOT EXPORT PUBLICLY
* @param {Client} client OpenFeature client
*
* **DO NOT EXPORT PUBLICLY**
* @internal
* @param {Provider} provider the provider to suspend for
* @param {Client} client the client to check for readiness
*/
export function suspendUntilReady(client: Client): Promise<void> {
let resolve: (value: unknown) => void;
let reject: () => void;
throw new Promise((_resolve, _reject) => {
resolve = _resolve;
reject = _reject;
client.addHandler(ProviderEvents.Ready, resolve);
client.addHandler(ProviderEvents.Error, reject);
}).finally(() => {
client.removeHandler(ProviderEvents.Ready, resolve);
client.removeHandler(ProviderEvents.Ready, reject);
});
export function suspendUntilInitialized(provider: Provider, client: Client) {
const statusPromiseRef = globalProviderSuspenseStatus.get(provider);
if (!statusPromiseRef) {
// Noop provider is never ready, so we resolve immediately
const statusPromise = provider !== NOOP_PROVIDER ? isProviderReady(client) : Promise.resolve();
// Storing the promise globally because

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: This comment is unfinished

globalProviderSuspenseStatus.set(provider, statusPromise);
// Use will throw the promise and React will trigger a rerender when it's resolved
use(statusPromise);
} else {
// Reuse the existing promise, use won't rethrow if the promise has settled.
use(statusPromiseRef);
}
}

/**
* Suspends until the provider has finished reconciling.
*
* **DO NOT EXPORT PUBLICLY**
* @internal
* @param {Client} client the client to check for readiness
*/
export function suspendUntilReconciled(client: Client) {
use(isProviderReady(client));
}

async function isProviderReady(client: Client) {
const controller = new AbortController();
try {
return await new Promise((resolve, reject) => {
client.addHandler(ProviderEvents.Ready, resolve, { signal: controller.signal });
client.addHandler(ProviderEvents.Error, reject, { signal: controller.signal });
});
} finally {
controller.abort();
}
}
53 changes: 53 additions & 0 deletions packages/react/src/internal/use.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/// <reference types="react/experimental" />
// This function is adopted from https://github.com/vercel/swr
import React from 'react';

/**
* Extends a Promise-like value to include status tracking.
* The extra properties are used to manage the lifecycle of the Promise, indicating its current state.
* More information can be found in the React RFE for the use hook.
* @see https://github.com/reactjs/rfcs/pull/229
*/
export type UsePromise<T> =
Promise<T> & {
status?: 'pending' | 'fulfilled' | 'rejected';
value?: T;
reason?: unknown;
};

/**
* React.use is a React API that lets you read the value of a resource like a Promise or context.
* It was officially added in React 19, so needs to be polyfilled to support older React versions.
* @param {UsePromise} thenable A thenable object that represents a Promise-like value.
* @returns {unknown} The resolved value of the thenable or throws if it's still pending or rejected.
*/
export const use =
React.use ||
// This extra generic is to avoid TypeScript mixing up the generic and JSX syntax
// and emitting an error.
// We assume that this is only for the `use(thenable)` case, not `use(context)`.
// https://github.com/facebook/react/blob/aed00dacfb79d17c53218404c52b1c7aa59c4a89/packages/react-server/src/ReactFizzThenable.js#L45
// eslint-disable-next-line @typescript-eslint/no-unused-vars
(<T, _>(thenable: UsePromise<T>): T => {
switch (thenable.status) {
case 'pending':
throw thenable;
case 'fulfilled':
return thenable.value as T;
case 'rejected':
throw thenable.reason;
default:
thenable.status = 'pending';
thenable.then(
(v) => {
thenable.status = 'fulfilled';
thenable.value = v;
},
(e) => {
thenable.status = 'rejected';
thenable.reason = e;
},
);
throw thenable;
}
});
2 changes: 1 addition & 1 deletion packages/react/src/provider/provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ type ProviderProps = {
* @param {ProviderProps} properties props for the context provider
* @returns {OpenFeatureProvider} context provider
*/
export function OpenFeatureProvider({ client, domain, children, ...options }: ProviderProps) {
export function OpenFeatureProvider({ client, domain, children, ...options }: ProviderProps): JSX.Element {
if (!client) {
client = OpenFeature.getClient(domain);
}
Expand Down
7 changes: 3 additions & 4 deletions packages/react/src/provider/use-open-feature-client.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import React from 'react';
import { Context } from '../internal';
import type { Client } from '@openfeature/web-sdk';
import { type Client } from '@openfeature/web-sdk';
import { MissingContextError } from '../internal/errors';

/**
* Get the {@link Client} instance for this OpenFeatureProvider context.
Expand All @@ -11,9 +12,7 @@ export function useOpenFeatureClient(): Client {
const { client } = React.useContext(Context) || {};

if (!client) {
throw new Error(
'No OpenFeature client available - components using OpenFeature must be wrapped with an <OpenFeatureProvider>. If you are seeing this in a test, see: https://openfeature.dev/docs/reference/technologies/client/web/react#testing',
);
throw new MissingContextError('No OpenFeature client available');
}

return client;
Expand Down
21 changes: 21 additions & 0 deletions packages/react/src/provider/use-open-feature-provider.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import React from 'react';
import { Context } from '../internal';
import { OpenFeature } from '@openfeature/web-sdk';
import type { Provider } from '@openfeature/web-sdk';
import { MissingContextError } from '../internal/errors';

/**
* Get the {@link Provider} bound to the domain specified in the OpenFeatureProvider context.
* Note that it isn't recommended to interact with the provider directly, but rather through
* an OpenFeature client.
* @returns {Provider} provider for this scope
*/
export function useOpenFeatureProvider(): Provider {
const openFeatureContext = React.useContext(Context);

if (!openFeatureContext) {
throw new MissingContextError('No OpenFeature context available');
}

return OpenFeature.getProvider(openFeatureContext.domain);
}
11 changes: 6 additions & 5 deletions packages/react/src/provider/use-when-provider-ready.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import { ProviderStatus } from '@openfeature/web-sdk';
import { useOpenFeatureClient } from './use-open-feature-client';
import { useOpenFeatureClientStatus } from './use-open-feature-client-status';
import type { ReactFlagEvaluationOptions } from '../options';
import { DEFAULT_OPTIONS, useProviderOptions, normalizeOptions, suspendUntilReady } from '../internal';
import { DEFAULT_OPTIONS, useProviderOptions, normalizeOptions, suspendUntilInitialized } from '../internal';
import { useOpenFeatureProvider } from './use-open-feature-provider';

type Options = Pick<ReactFlagEvaluationOptions, 'suspendUntilReady'>;

Expand All @@ -14,14 +15,14 @@ type Options = Pick<ReactFlagEvaluationOptions, 'suspendUntilReady'>;
* @returns {boolean} boolean indicating if provider is {@link ProviderStatus.READY}, useful if suspense is disabled and you want to handle loaders on your own
*/
export function useWhenProviderReady(options?: Options): boolean {
const client = useOpenFeatureClient();
const status = useOpenFeatureClientStatus();
// highest priority > evaluation hook options > provider options > default options > lowest priority
const defaultedOptions = { ...DEFAULT_OPTIONS, ...useProviderOptions(), ...normalizeOptions(options) };
const client = useOpenFeatureClient();
const status = useOpenFeatureClientStatus();
const provider = useOpenFeatureProvider();

// suspense
if (defaultedOptions.suspendUntilReady && status === ProviderStatus.NOT_READY) {
suspendUntilReady(client);
suspendUntilInitialized(provider, client);
}

return status === ProviderStatus.READY;
Expand Down
Loading