Skip to main content

Finalize

Finalizing (or closing) a context publishes any unpublished events before "sealing" it. Any track calls after a context has been finalized will throw an error.

Some examples of when you may want to finalize a context:

  • When your application is being destroyed.
  • When a user logs out. In this case, you no longer know if the current user is the same user as before. It is best to finalize the original context, create a new one and pass it an anonymous_id.

Call the context.finalize() method before letting a process using the SDK exit, as this method gracefully shuts down the SDK by clearing caches, and closing connections. It will also call context.publish() to flush the remaining unpublished impressions.

// You can just finalize and remove the variable reference
context.finalize();
context = null;
// finalize() returns a promise, so if you want to
// navigate to another page without losing impressions, you
// can do that once the promise resolves.
context.finalize().then(function () {
context = null;
document.location.replace("another_page");
});
caution

After finalize() is called and finishes, any subsequent invocations to the treatment() method will still return the right variant, but will result in a warning to let you know that you might be losing impressions.