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