File tree Expand file tree Collapse file tree 1 file changed +23
-0
lines changed Expand file tree Collapse file tree 1 file changed +23
-0
lines changed Original file line number Diff line number Diff line change @@ -6,6 +6,10 @@ type Data = {
6
6
error ?: string
7
7
}
8
8
9
+ // In-memory cache
10
+ let cachedUsers : { value : number ; timestamp : number } | null = null
11
+ const CACHE_DURATION = 60 * 1000 // 1 minute
12
+
9
13
/**
10
14
* API endpoint to get active user count from PostHog
11
15
* This keeps the PostHog API key secure on the server side
@@ -23,19 +27,38 @@ export default async function handler(
23
27
}
24
28
25
29
try {
30
+ const now = Date . now ( )
31
+
32
+ // Serve from cache if not expired
33
+ if ( cachedUsers && now - cachedUsers . timestamp < CACHE_DURATION ) {
34
+ return res . status ( 200 ) . json ( {
35
+ activeUsers : cachedUsers . value ,
36
+ success : true ,
37
+ } )
38
+ }
39
+
40
+ // Fetch fresh data
26
41
const activeUsers = await fetchActiveUsersFromPostHog ( )
27
42
28
43
if ( activeUsers !== null ) {
44
+ cachedUsers = {
45
+ value : activeUsers ,
46
+ timestamp : now ,
47
+ }
48
+
29
49
return res . status ( 200 ) . json ( {
30
50
activeUsers,
31
51
success : true ,
32
52
} )
33
53
}
54
+
55
+ throw new Error ( 'Failed to retrieve active users' )
34
56
} catch ( error ) {
35
57
console . error ( 'Error in active-users API:' , error )
36
58
return res . status ( 500 ) . json ( {
37
59
activeUsers : 0 ,
38
60
success : false ,
61
+ error : 'Internal server error' ,
39
62
} )
40
63
}
41
64
}
You can’t perform that action at this time.
0 commit comments