@nuskin/react-foundation-sdk
v1.0.0-mdigi-12165.2
Published
React hook for feature flags management for NuSkin. Supports Zustand state, cookie-based user ID storage, and environment-based overrides.
Downloads
737
Readme
react-foundation-sdk
A React hook library to retrieve feature flags and check if they are enabled or not. This is a React-compatible version of the original ns-feature-flags library that uses cookies instead of session storage for user ID management.
Installation
npm install @nuskin/react-foundation-sdkOr with yarn:
yarn add @nuskin/react-foundation-sdkUsage
Basic Usage
import { useFeatureFlags } from '@nuskin/react-foundation-sdk';
function MyComponent() {
const { isEnabled, retrieveToggles, toggles, loading, error } = useFeatureFlags();
// Fetch toggles on component mount
React.useEffect(() => {
const fetchFlags = async () => {
await retrieveToggles('https://devapi.cloud.nuskin.com/feature-flags/v1/proxy');
};
fetchFlags();
}, [retrieveToggles]);
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return (
<div>
{isEnabled('feature1') && <p>Feature 1 is enabled!</p>}
{isEnabled('feature2') && <p>Feature 2 is enabled!</p>}
</div>
);
}With User ID
You can specify a userId to retrieve flags for a specific user:
const { setCookieUser } = useFeatureFlags();
// Set the user ID in a cookie (default 365 days)
setCookieUser('qa-user', 365);
// Or pass userId directly to methods
await retrieveToggles(url, 'qa-user');Retrieve Production Toggles
import { useFeatureFlags } from '@nuskin/react-foundation-sdk';
function MyComponent() {
const { retrieveProductionToggles } = useFeatureFlags();
React.useEffect(() => {
const fetchFlags = async () => {
await retrieveProductionToggles('optional-userId');
};
fetchFlags();
}, [retrieveProductionToggles]);
// ... rest of component
}Retrieve Toggles Based on Environment
The hook can automatically determine the correct endpoint based on hostname or environment:
const { retrieveTogglesBasedOnEnvironment } = useFeatureFlags();
// Browser will auto-detect hostname
React.useEffect(() => {
const fetchFlags = async () => {
await retrieveTogglesBasedOnEnvironment();
};
fetchFlags();
}, [retrieveTogglesBasedOnEnvironment]);
// Or provide explicit options
React.useEffect(() => {
const fetchFlags = async () => {
await retrieveTogglesBasedOnEnvironment({
environment: 'dev',
userId: 'qa',
});
};
fetchFlags();
}, [retrieveTogglesBasedOnEnvironment]);Cookie-Based User ID Management
This React version replaces session storage with cookies for managing user IDs. This is more suitable for React applications and provides persistence across browser restarts.
Setting User ID
const { setCookieUser } = useFeatureFlags();
// Set user ID for 365 days (default)
setCookieUser('my-user-id');
// Set user ID for custom duration
setCookieUser('my-user-id', 30); // 30 daysGetting User ID
const { getCookieUser } = useFeatureFlags();
const userId = getCookieUser();Deleting User ID
const { deleteCookieUser } = useFeatureFlags();
deleteCookieUser();Overriding Flag Values
To explicitly set a flag value, like in integration tests or local development, you can set values in the query string or in cookies.
Both the query string and cookie values use the same key names. To enable flags, use $enableFeatureFlags; to disable them, use $disableFeatureFlags.
Query String Example
?$enableFeatureFlags=feature1,feature2&$disableFeatureFlags=feature3Cookie Example
Set in-browser dev tools console:
// Enable flags
document.cookie = '$enableFeatureFlags=feature1,feature2; path=/';
// Disable flags
document.cookie = '$disableFeatureFlags=feature3; path=/';Supported Environments
The library automatically maps hostnames and environment names to the correct endpoints:
Dev Environment
devlocalhost:[port]- Any hostname containing
pubawsorauthaws - Any hostname containing
aem.dev.nuskin.io tools.dev.nuskin.iodev.nuskin.comdevapi.cloud.nuskin.comdevelopment
Test Environment
testtest.nuskin.comapps.dev.nuskin.iotools.tst.nuskin.io- Any hostname ending with
.test.mynuskin.com testapi.cloud.nuskin.comwww.tst.nuskin.io
Stage Environment
stagetools.stage.nuskin.iostage.nuskin.comstageapi.cloud.nuskin.com
Production Environment
prodproductionwww.nuskin.comtools.nuskin.ioapi.cloud.nuskin.com- Any hostname ending with
.mynuskin.com
Hook Return Values
The useFeatureFlags hook returns an object with the following properties:
State
toggles:Set<string>- Set of enabled feature flag namesloading:boolean- Whether flags are being fetchederror:Error | null- Error object if fetch failed
Methods
isEnabled(toggleName: string):boolean- Check if a flag is enabledretrieveToggles(url: string, userId?: string):Promise<Set<string>>- Fetch flags from URLretrieveProductionToggles(userId?: string):Promise<Set<string>>- Fetch production flagsretrieveTogglesBasedOnEnvironment(options?: FeatureFlagOptions):Promise<Set<string>>- Fetch based on environmentgetEnabledFlags():Set<string>- Get a copy of enabled flags
Cookie Methods
setCookieUser(userId: string, days?: number):void- Set user ID in cookiegetCookieUser():string- Get user ID from cookiedeleteCookieUser():void- Delete user ID cookie
Performance Considerations
Important: Developer should NOT invoke retrieveToggles() / retrieveProductionToggles() repeatedly within the same component render cycle because it will incur network cost by hitting the feature flags endpoint.
The hook has a 5-second threshold that prevents multiple network calls if the same function is called repeatedly within that period. However, this does not prevent multiple network calls if more than one instance of the hook is used.
Best Practice: Call flag retrieval methods only in useEffect callbacks and cache the results.
React.useEffect(() => {
const fetchFlags = async () => {
await retrieveTogglesBasedOnEnvironment();
};
fetchFlags();
}, []); // Empty dependency array - only runs once on mountTypeScript Support
The library includes full TypeScript support with type definitions. Import types as needed:
import { useFeatureFlags } from '@nuskin/react-foundation-sdk';
import type { UseFeatureFlagsReturn, FeatureFlagOptions } from '@nuskin/react-foundation-sdk';
function MyComponent() {
const flags: UseFeatureFlagsReturn = useFeatureFlags();
// ...
}Key Differences from Original Library
| Feature | Original | React Version |
| ---------------- | ------------------------------------- | ------------------------------------- |
| Storage | Session Storage | Cookies |
| User ID Key | $featureFlagUserId (sessionStorage) | $featureFlagUserId (cookie) |
| API | CommonJS exports | React hook |
| State Management | Module-level state | React useState |
| Integration | Direct function calls | Hook integration with React lifecycle |
License
MIT
