Skip to content

Instantly share code, notes, and snippets.

@superstrong
Last active March 9, 2016 00:43
Show Gist options
  • Save superstrong/f468fd0ebdd6da2952e7 to your computer and use it in GitHub Desktop.
Save superstrong/f468fd0ebdd6da2952e7 to your computer and use it in GitHub Desktop.
Segment db-less identify
This code is for a website that collects email addresses but no registrations (e.g., passwords, etc.). The requirements for the project go further, but this is a necessary first step.
Project requirements:
- Simplify tracking implementation
- Use a userId, not email address, as primary key
- Avoid using a database on email-only website
Segment is useful as a canonical tracker -- a single place to track identity, pageviews. It works best, though, when a server generates a userId and calls `identify`, ensuring the userId passed through to all connected services.
Here, in lieu of a server-generated userId, we check for a Segment userId in the cookie. If it exists, we use it. If it doesn't, we grab Segment's anonymousId and re-use it as userId. This, along with the other form fields in a simple form, are used in an `identify` call that ensures all connected services get the same userId.
The form itself doesn't actuall post data anywhere. The user data flow through to the other services via the Segment calls.
###
<form id="foo">
<label for="fullname">Full Name</label>
<input type="text" id="full-name" class="form-control" name="fullname">
<label for="email">Email</label>
<input type="email" id="email-address" class="form-control" name="email">
<input type="submit" class="btn btn-default" value="Confirm">
</form>
###
<script type="text/javascript">
[Segment analytics.js goes here]
</script>
###
<script type="text/javascript">
$("#foo").submit(function (event) {
// Stop the form from submitting
event.preventDefault();
// Get userId from Segment cookie if it exists. If it doesn't, generate a UUID and store it.
var segmentId = analytics.user().id();
var anonymousId = analytics.user().anonymousId();
if (segmentId === null) {
var userid = anonymousId;
} else {
var userid = segmentId;
}
var email = document.getElementById('email-address').value;
var fullname = document.getElementById('full-name').value;
// Run Segment's identify and track calls
analytics.identify(userid, {
name: fullname,
email: email
});
analytics.track('Made Contact', {
source: 'Website Form'
});
// Hide the contents of the form area and replace with a success message hidden by default
document.getElementById("modal-form").style.display = "none";
document.getElementById("modal-success").style.display = "block";
return false;
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment