Skip to content

Commit d88c90e

Browse files
authored
Add more guidance to the Statsig example (#970)
Update the Statsig example to prevent rules getting out of sync.
1 parent 0c03e43 commit d88c90e

File tree

1 file changed

+19
-4
lines changed

1 file changed

+19
-4
lines changed

edge-middleware/ab-testing-statsig/middleware.ts

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,13 @@ export const config = {
1717
matcher: '/',
1818
}
1919

20+
// Manually sync as the SDK cannot poll for updates across requests since
21+
// Edge Middleware does not allow for timers outside of the request handler
22+
//
23+
// See https://docs.statsig.com/integrations/vercel/#polling-for-updates-v5130
24+
let lastSyncTime = 0
25+
const syncInterval = 60_000 // 1 minute
26+
2027
export async function middleware(req: NextRequest, event: NextFetchEvent) {
2128
// Get the user ID from the cookie or get a new one
2229
let userId = req.cookies.get(UID_COOKIE)?.value
@@ -39,17 +46,25 @@ export async function middleware(req: NextRequest, event: NextFetchEvent) {
3946
// that the ID List will not apply in most cases as it will only get fetched
4047
// after the experiment ran
4148
initStrategyForIDLists: 'none',
42-
// 🚨 This setting will prevent Statsig from making any network requests,
43-
// thus ensuring middleware stays extremly fast.
44-
localMode: true,
4549
// This makes Statsig load experiments from Edge Config
4650
dataAdapter,
4751
// Disable any syncing to prevent network activity, as Edge Config will
4852
// return the latest values anyhow, and as ID Lists are disabled.
4953
disableIdListsSync: true,
50-
disableRulesetsSync: true,
5154
})
5255

56+
// init within middleware so we get the actual time, as Date.now() will not
57+
// return accourate time outside of the request lifecycle.
58+
//
59+
// Avoid syncing initially as we just initialized and will sync on the
60+
// first request anyway.
61+
if (lastSyncTime === 0) {
62+
lastSyncTime = Date.now()
63+
} else if (lastSyncTime < Date.now() - syncInterval) {
64+
lastSyncTime = Date.now()
65+
event.waitUntil(Statsig.syncConfigSpecs())
66+
}
67+
5368
const experiment = Statsig.getExperimentWithExposureLoggingDisabledSync(
5469
{ userID: userId },
5570
EXPERIMENT

0 commit comments

Comments
 (0)