Single Page Applications

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
<head>
  <!-- Replace the digits at the end of the URL with your Castle App ID -->
  <script src="https://d2t77mnxyo7adj.cloudfront.net/v1/c.js?123456789012345"></script>
  <script>
    _castle('autoTrack', false); // Disable Castle from auto-sending tracking pixels on page load
  </script>

  ...
</head>

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.

<body>
  ...

  <!-- Once you are able to identify the user -->
  <script>
    _castle('identify', '{current_user_id}'); // Set the current user's id
    _castle('trackPageview'); // Manually send a Castle tracking pixel
  </script>

  ...
</body>

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.

_castle(trackPageview);

Note: By default, _castle(‘trackPageview’); appends the current URL and page title as metadata on the event. If you prefer to manually set the URL and title, you can pass them as parameters like this:
_castle('trackPageview', 'http://castle.io', 'Home of the Greatest ATO Solution');

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.

_castle('reset');
_castle('trackPageview');

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('identify', response.user.id);
_castle('secure', response.token);
_castle('trackPageview');