npm package: @nuskin/react-foundation-sdk
Description: React hook for feature flags management for NuSkin. Supports Zustand state, cookie-based user ID storage, and environment-based overrides.
Author: Kelvin Lau
Latest version: 1.0.0-mdigi-12165.2

# 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

```sh
npm install @nuskin/react-foundation-sdk
```

Or with yarn:

```sh
yarn add @nuskin/react-foundation-sdk
```

## Usage

### Basic Usage

```javascript
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:

```javascript
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

```javascript
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:

```javascript
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

```javascript
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 days
```

### Getting User ID

```javascript
const { getCookieUser } = useFeatureFlags();

const userId = getCookieUser();
```

### Deleting User ID

```javascript
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=feature3
```

### Cookie Example

Set in-browser dev tools console:

```javascript
// 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

- `dev`
- `localhost:[port]`
- Any hostname containing `pubaws` or `authaws`
- Any hostname containing `aem.dev.nuskin.io`
- `tools.dev.nuskin.io`
- `dev.nuskin.com`
- `devapi.cloud.nuskin.com`
- `development`

### Test Environment

- `test`
- `test.nuskin.com`
- `apps.dev.nuskin.io`
- `tools.tst.nuskin.io`
- Any hostname ending with `.test.mynuskin.com`
- `testapi.cloud.nuskin.com`
- `www.tst.nuskin.io`

### Stage Environment

- `stage`
- `tools.stage.nuskin.io`
- `stage.nuskin.com`
- `stageapi.cloud.nuskin.com`

### Production Environment

- `prod`
- `production`
- `www.nuskin.com`
- `tools.nuskin.io`
- `api.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 names
- `loading`: `boolean` - Whether flags are being fetched
- `error`: `Error | null` - Error object if fetch failed

### Methods

- `isEnabled(toggleName: string)`: `boolean` - Check if a flag is enabled
- `retrieveToggles(url: string, userId?: string)`: `Promise<Set<string>>` - Fetch flags from URL
- `retrieveProductionToggles(userId?: string)`: `Promise<Set<string>>` - Fetch production flags
- `retrieveTogglesBasedOnEnvironment(options?: FeatureFlagOptions)`: `Promise<Set<string>>` - Fetch based on environment
- `getEnabledFlags()`: `Set<string>` - Get a copy of enabled flags

### Cookie Methods

- `setCookieUser(userId: string, days?: number)`: `void` - Set user ID in cookie
- `getCookieUser()`: `string` - Get user ID from cookie
- `deleteCookieUser()`: `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.

```javascript
React.useEffect(() => {
    const fetchFlags = async () => {
        await retrieveTogglesBasedOnEnvironment();
    };
    fetchFlags();
}, []); // Empty dependency array - only runs once on mount
```

## TypeScript Support

The library includes full TypeScript support with type definitions. Import types as needed:

```typescript
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