fresh-keyboard-9333
02/15/2023, 9:50 PMfresh-football-47124
fresh-keyboard-9333
02/16/2023, 4:23 PMfresh-football-47124
fresh-keyboard-9333
02/16/2023, 4:25 PMuse(req: Request, res: Response, next: NextFunction): void {
const id = getUserIdFromRequest(req);
const currentGrowthBookUserId = this.growthbook.getAttributes().id;
if (id && currentGrowthBookUserId !== id) {
this.growthbook.setAttributes({
id,
});
}
next();
}
setAttributes
do async tasks in the background that could cause race conditions?fresh-football-47124
fresh-keyboard-9333
02/16/2023, 4:26 PMfresh-football-47124
future-teacher-7046
fresh-keyboard-9333
02/17/2023, 4:15 PMfuture-teacher-7046
apiHost
and clientKey
), it has caching by default. If you're implementing your own fetching, make sure to do that outside of the request and re-use the same JSON object for each SDK instance.
For express, it would look something like this:
app.use(function(req, res, next) {
// Create a GrowthBook Context
req.growthbook = new GrowthBook({
apiHost: "<https://cdn.growthbook.io>",
clientKey: "sdk-abc123",
attributes: {
// TODO: real targeting attributes from the request
id: req.cookies.ID
},
trackingCallback: (experiment, result) => {
// TODO: Use your real analytics tracking system
console.log("Viewed Experiment", {
experimentId: experiment.key,
variationId: result.variationId
});
}
});
// Clean up at the end of the request
res.on('close', () => req.growthbook.destroy());
// Wait for features to load (will be cached in-memory for future requests)
req.growthbook.loadFeatures()
.then(() => next())
.catch((e) => {
console.error("Failed to load features from GrowthBook", e);
next();
})
})
fresh-keyboard-9333
02/17/2023, 5:21 PM