prismic.io experiments with the REST API

Once you've created an experiment in the Writing Room, there are a few more things to be done in order to activate it on your site.

Include the experiments snippet your HTML code

This code should be present in all pages. The googleId is a property of the Experiment object that can be retrieved from api.experiments.current.

Copy
<!-- Replace {googleId} by the GoogleId of the current experiment & replace {your-api-endpoint} by your API's endpoint -->
<script>
  window.prismic = { endpoint: '{your-api-endpoint}' };
  window.googleId = '{googleId}';
</script>
<script>
  {code from google analytics}
</script>
<script src="//static.cdn.prismic.io/prismic.min.js"></script>
<script>prismic.startExperiment(window.googleId);</script>

Retrieving the correct Ref for the current user

Once the HTML snippet above is included, users will receive a cookie setting the variation assign to them, ensuring a given user always sees the same variation. Every call to the API should now use the corresponding Ref rather than the Master Ref.

The way to retrieve the cookie value from the HTTP request depends on the framework, so you may need to adapt the following code snippet for your usage. If your project is based on a recent version of a starter kit, the code should already be there.

Copy
// From the browser in javascript
var experimentCookie = prismic.startExperiment ? prismic.utils.docCookies.getItem('io.prismic.experiment') : null;
var experimentRef = experimentCookie ? api.experiments.refFromCookie(experimentCookie) : null;
var ref = experimentRef || api.data.master.ref;