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 = {
66 error ?: string
77}
88
9+ // In-memory cache
10+ let cachedUsers : { value : number ; timestamp : number } | null = null
11+ const CACHE_DURATION = 60 * 1000 // 1 minute
12+
913/**
1014 * API endpoint to get active user count from PostHog
1115 * This keeps the PostHog API key secure on the server side
@@ -23,19 +27,38 @@ export default async function handler(
2327 }
2428
2529 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
2641 const activeUsers = await fetchActiveUsersFromPostHog ( )
2742
2843 if ( activeUsers !== null ) {
44+ cachedUsers = {
45+ value : activeUsers ,
46+ timestamp : now ,
47+ }
48+
2949 return res . status ( 200 ) . json ( {
3050 activeUsers,
3151 success : true ,
3252 } )
3353 }
54+
55+ throw new Error ( 'Failed to retrieve active users' )
3456 } catch ( error ) {
3557 console . error ( 'Error in active-users API:' , error )
3658 return res . status ( 500 ) . json ( {
3759 activeUsers : 0 ,
3860 success : false ,
61+ error : 'Internal server error' ,
3962 } )
4063 }
4164}
You can’t perform that action at this time.
0 commit comments