We recommend creating a brand new instance for every request. Creating an instance is fast and cheap, the only expensive part is fetching the list of features from the API. If you're using the new built-in fetching (by specifying
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();
})
})