Single-page Application

If you have a single-page app where content is swapped out on the client side but without any page refreshes, you'll need to split up the Castle.js integration into multiple steps.

Step 1: Include the snippet

Paste the JavaScript snippet into the section of all your pages, but in contrast to the baseline implementation, you’ll need to make the following two changes:

  1. Leave out the identify part.
  2. Disable automatic tracking of page views
<script type=text/javascript">
  (function(e,t,n,r){function i(e,n){e=t.createElement("script");e.async=1;e.src=r;n=t.getElementsByTagName("script")[0];n.parentNode.insertBefore(e,n)}e[n]=e[n]||function(){(e[n].q=e[n].q||[]).push(arguments)};e.attachEvent?e.attachEvent("onload",i):e.addEventListener("load",i,false)})(window,document,"_castle","//")
  // Get your App ID here:
  _castle('setAppId', '123456789012');
  _castle('autoTrack', false);

Step 2: Logging in the user

Once you have a logged the user into your site via an asynchronous API call, you'll call the following from your single-page app. You’ll also need to track a page view after the call to make sure the user ID is tracked to Castle.


Step 3: Tracking page views

Since we’ve now turned off autoTrack, you will need to call the following in order to track a page view every time the URL changes. It’s recommended that you only track this for full view transitions, and for example not in-page updates to the URL hash.


Step 4: Logging out the user

In a similar way to how you logged in the user, you’ll also need to reset the state on logout. Finish it up by tracking a page view to ensure the reset call reaches the Castle API.


Step 5: Secure Mode

The guide for Secure Mode mentions rendering the secure token into the HTML code, but since the user won't be logged in during page load, this approach is not an option for single-page apps. Instead you'll need to return generate the secure token during the login call and then call the following right after identify:

_castle('secure', response.token);