configcat.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import * as configcat from 'configcat-js'
  2. let client: configcat.IConfigCatClient
  3. /**
  4. * To set up ConfigCat for another app
  5. * - Declare `FeatureFlagProvider` at the _app level
  6. * - Pass in `getFlags` as `getConfigCatFlags` into `FeatureFlagProvider`
  7. * - [Joshen] Wondering if this should just be baked into FeatureFlagProvider, rather than passed as a prop
  8. * - Ensure that your app has the `NEXT_PUBLIC_CONFIGCAT_PROXY_URL` env var
  9. * - [Joshen] Wondering if we can just set a default value for each env var, so can skip setting up env var in Vercel
  10. * - Verify that your flags are now loading by console logging `flagValues` in `FeatureFlagProvider`'s useEffect
  11. * - Can now use ConfigCat feature flags with the `useFlag` hook
  12. */
  13. async function getClient() {
  14. if (client) return client
  15. const proxyUrl = process.env.NEXT_PUBLIC_CONFIGCAT_PROXY_URL
  16. const sdkKey = process.env.NEXT_PUBLIC_CONFIGCAT_SDK_KEY
  17. if (!sdkKey && !proxyUrl) {
  18. console.log('Skipping ConfigCat set up as env vars are not present')
  19. return undefined
  20. }
  21. const options = { pollIntervalSeconds: 7 * 60 } // 7 minutes
  22. try {
  23. if (proxyUrl) {
  24. const proxyClient = configcat.getClient(
  25. 'configcat-proxy/frontend-v2',
  26. configcat.PollingMode.AutoPoll,
  27. { ...options, baseUrl: proxyUrl }
  28. )
  29. const cacheState = await proxyClient.waitForReady()
  30. if (cacheState !== configcat.ClientCacheState.NoFlagData) {
  31. client = proxyClient
  32. return client
  33. }
  34. proxyClient.dispose()
  35. }
  36. if (sdkKey) {
  37. client = configcat.getClient(sdkKey, configcat.PollingMode.AutoPoll, options)
  38. return client
  39. }
  40. console.error('ConfigCat proxy unreachable and SDK key is missing')
  41. return undefined
  42. } catch (error: any) {
  43. console.error(`Failed to get ConfigCat client: ${error.message}`)
  44. return undefined
  45. }
  46. }
  47. export async function getFlags(userEmail: string = '', customAttributes?: Record<string, string>) {
  48. const client = await getClient()
  49. const _customAttributes = {
  50. ...customAttributes,
  51. is_staff: !!userEmail ? userEmail.includes('@briven.').toString() : 'false',
  52. }
  53. if (!client) {
  54. return []
  55. }
  56. await client.waitForReady()
  57. if (userEmail) {
  58. return client.getAllValuesAsync(
  59. new configcat.User(userEmail, undefined, undefined, _customAttributes)
  60. )
  61. } else {
  62. return client.getAllValuesAsync(
  63. new configcat.User('anonymous', undefined, undefined, _customAttributes)
  64. )
  65. }
  66. }