v0.0.13: Remove useConfig dependency from client hooks

Makes client hooks work outside of Payload Admin UI context by:
- Adding FeatureFlagOptions parameter to all hooks for configuration
- Using window.location.origin as default serverURL when in browser
- Removing @payloadcms/ui dependency from client hooks
- Allowing custom serverURL, apiPath, and collectionSlug configuration

This fixes the webpack error "_payloadcms_ui__WEBPACK_IMPORTED_MODULE_1__.b() is undefined"
when using the hooks in frontend applications.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2025-10-03 18:25:32 +02:00
parent e26d895864
commit 4f802c8cc9
3 changed files with 45 additions and 18 deletions

View File

@@ -1,6 +1,6 @@
{ {
"name": "@xtr-dev/payload-feature-flags", "name": "@xtr-dev/payload-feature-flags",
"version": "0.0.12", "version": "0.0.13",
"description": "Feature flags plugin for Payload CMS - manage feature toggles, A/B tests, and gradual rollouts", "description": "Feature flags plugin for Payload CMS - manage feature toggles, A/B tests, and gradual rollouts",
"license": "MIT", "license": "MIT",
"type": "module", "type": "module",

View File

@@ -7,4 +7,5 @@ export {
useRolloutCheck, useRolloutCheck,
withFeatureFlag, withFeatureFlag,
type FeatureFlag, type FeatureFlag,
type FeatureFlagOptions,
} from '../hooks/client.js' } from '../hooks/client.js'

View File

@@ -1,6 +1,5 @@
'use client' 'use client'
import React, { useCallback, useEffect, useState } from 'react' import React, { useCallback, useEffect, useState } from 'react'
import { useConfig } from '@payloadcms/ui'
export interface FeatureFlag { export interface FeatureFlag {
name: string name: string
@@ -14,18 +13,36 @@ export interface FeatureFlag {
metadata?: any metadata?: any
} }
export interface FeatureFlagOptions {
serverURL?: string
apiPath?: string
collectionSlug?: string
}
// Helper to get config from options or defaults
function getConfig(options?: FeatureFlagOptions) {
const serverURL = options?.serverURL ||
(typeof window !== 'undefined' ? window.location.origin : '') ||
''
const apiPath = options?.apiPath || '/api'
const collectionSlug = options?.collectionSlug || 'feature-flags'
return { serverURL, apiPath, collectionSlug }
}
/** /**
* Hook to fetch all active feature flags from the API * Hook to fetch all active feature flags from the API
*/ */
export function useFeatureFlags( export function useFeatureFlags(
initialFlags: Partial<FeatureFlag>[] initialFlags: Partial<FeatureFlag>[],
options?: FeatureFlagOptions
): { ): {
flags: Partial<FeatureFlag>[] flags: Partial<FeatureFlag>[]
loading: boolean loading: boolean
error: string | null error: string | null
refetch: () => Promise<void> refetch: () => Promise<void>
} { } {
const { config } = useConfig() const { serverURL, apiPath, collectionSlug } = getConfig(options)
const [flags, setFlags] = useState<Partial<FeatureFlag>[]>(initialFlags) const [flags, setFlags] = useState<Partial<FeatureFlag>[]>(initialFlags)
const [loading, setLoading] = useState(true) const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null) const [error, setError] = useState<string | null>(null)
@@ -41,7 +58,7 @@ export function useFeatureFlags(
? `?where[name][in]=${names.join(',')}&limit=1000` ? `?where[name][in]=${names.join(',')}&limit=1000`
: '?limit=1000' : '?limit=1000'
const response = await fetch(`${config.serverURL}${config.routes.api}/feature-flags${query}`) const response = await fetch(`${serverURL}${apiPath}/${collectionSlug}${query}`)
if (!response.ok) { if (!response.ok) {
throw new Error(`Failed to fetch feature flags: ${response.statusText}`) throw new Error(`Failed to fetch feature flags: ${response.statusText}`)
@@ -77,7 +94,7 @@ export function useFeatureFlags(
} finally { } finally {
setLoading(false) setLoading(false)
} }
}, [config.serverURL, config.routes.api, initialFlags]) }, [serverURL, apiPath, collectionSlug, initialFlags])
useEffect(() => { useEffect(() => {
void fetchFlags() void fetchFlags()
@@ -89,13 +106,16 @@ export function useFeatureFlags(
/** /**
* Hook to check if a specific feature flag is enabled * Hook to check if a specific feature flag is enabled
*/ */
export function useFeatureFlag(flagName: string): { export function useFeatureFlag(
flagName: string,
options?: FeatureFlagOptions
): {
isEnabled: boolean isEnabled: boolean
flag: Partial<FeatureFlag> | null flag: Partial<FeatureFlag> | null
loading: boolean loading: boolean
error: string | null error: string | null
} { } {
const { flags, loading, error } = useFeatureFlags([{ name: flagName }]) const { flags, loading, error } = useFeatureFlags([{ name: flagName }], options)
const flag = flags.find(f => f.name === flagName) || null const flag = flags.find(f => f.name === flagName) || null
const isEnabled = flag?.enabled || false const isEnabled = flag?.enabled || false
@@ -106,13 +126,16 @@ export function useFeatureFlag(flagName: string): {
/** /**
* Hook to fetch a specific feature flag from the API * Hook to fetch a specific feature flag from the API
*/ */
export function useSpecificFeatureFlag(flagName: string): { export function useSpecificFeatureFlag(
flagName: string,
options?: FeatureFlagOptions
): {
flag: FeatureFlag | null flag: FeatureFlag | null
loading: boolean loading: boolean
error: string | null error: string | null
refetch: () => Promise<void> refetch: () => Promise<void>
} { } {
const { config } = useConfig() const { serverURL, apiPath, collectionSlug } = getConfig(options)
const [flag, setFlag] = useState<FeatureFlag | null>(null) const [flag, setFlag] = useState<FeatureFlag | null>(null)
const [loading, setLoading] = useState(true) const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null) const [error, setError] = useState<string | null>(null)
@@ -124,7 +147,7 @@ export function useSpecificFeatureFlag(flagName: string): {
// Use Payload's native collection API with query filter // Use Payload's native collection API with query filter
const response = await fetch( const response = await fetch(
`${config.serverURL}${config.routes.api}/feature-flags?where[name][equals]=${flagName}&limit=1` `${serverURL}${apiPath}/${collectionSlug}?where[name][equals]=${flagName}&limit=1`
) )
if (!response.ok) { if (!response.ok) {
@@ -153,7 +176,7 @@ export function useSpecificFeatureFlag(flagName: string): {
} finally { } finally {
setLoading(false) setLoading(false)
} }
}, [config.serverURL, config.routes.api, flagName]) }, [serverURL, apiPath, collectionSlug, flagName])
useEffect(() => { useEffect(() => {
void fetchFlag() void fetchFlag()
@@ -167,14 +190,15 @@ export function useSpecificFeatureFlag(flagName: string): {
*/ */
export function useVariantSelection( export function useVariantSelection(
flagName: string, flagName: string,
userId: string userId: string,
options?: FeatureFlagOptions
): { ): {
variant: string | null variant: string | null
flag: FeatureFlag | null flag: FeatureFlag | null
loading: boolean loading: boolean
error: string | null error: string | null
} { } {
const { flag, loading, error } = useSpecificFeatureFlag(flagName) const { flag, loading, error } = useSpecificFeatureFlag(flagName, options)
const variant = flag?.enabled && flag.variants const variant = flag?.enabled && flag.variants
? selectVariantForUser(userId, flag.variants) ? selectVariantForUser(userId, flag.variants)
@@ -188,14 +212,15 @@ export function useVariantSelection(
*/ */
export function useRolloutCheck( export function useRolloutCheck(
flagName: string, flagName: string,
userId: string userId: string,
options?: FeatureFlagOptions
): { ): {
isInRollout: boolean isInRollout: boolean
flag: FeatureFlag | null flag: FeatureFlag | null
loading: boolean loading: boolean
error: string | null error: string | null
} { } {
const { flag, loading, error } = useSpecificFeatureFlag(flagName) const { flag, loading, error } = useSpecificFeatureFlag(flagName, options)
const isInRollout = flag?.enabled const isInRollout = flag?.enabled
? checkUserInRollout(userId, flag.rolloutPercentage || 100) ? checkUserInRollout(userId, flag.rolloutPercentage || 100)
@@ -253,13 +278,14 @@ function checkUserInRollout(userId: string, percentage: number): boolean {
*/ */
export function withFeatureFlag<P extends Record<string, any>>( export function withFeatureFlag<P extends Record<string, any>>(
flagName: string, flagName: string,
FallbackComponent?: React.ComponentType<P> FallbackComponent?: React.ComponentType<P>,
options?: FeatureFlagOptions
) { ) {
return function FeatureFlagWrapper( return function FeatureFlagWrapper(
WrappedComponent: React.ComponentType<P> WrappedComponent: React.ComponentType<P>
): React.ComponentType<P> { ): React.ComponentType<P> {
return function WithFeatureFlagComponent(props: P): React.ReactElement | null { return function WithFeatureFlagComponent(props: P): React.ReactElement | null {
const { isEnabled, loading } = useFeatureFlag(flagName) const { isEnabled, loading } = useFeatureFlag(flagName, options)
if (loading) { if (loading) {
return null // or a loading spinner return null // or a loading spinner