Cookie Session Tracking System
Cookie Session Tracking System - Technical Documentation
Overview
This document explains the implementation of a client-side cookie-based session tracking system used to manage user experience states in the GDB Data Explorer application. The system tracks whether users have seen specific UI modals and adapts the interface accordingly.
System Architecture
Core Components
- Cookie Management Functions (JavaScript)
- State Detection Logic (JavaScript)
- UI Adaptation System (Dynamic HTML/CSS)
- User Flow Control (Event-driven)
Implementation Details
1. Cookie Management Functions
setCookie(name, value, days)
function setCookie(name, value, days) {
let expires = "";
if (days) {
const date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
Purpose: Creates browser cookies with configurable expiration Parameters:
name: Cookie identifier stringvalue: Cookie value (stored as string)days: Expiration in days (optional, defaults to session cookie)
Technical Details:
- Uses
document.cookieAPI for client-side storage - Calculates expiration timestamp in UTC format
- Sets path to root (
/) for site-wide accessibility - No domain restriction (inherits from current domain)
getCookie(name)
function getCookie(name) {
const nameEQ = name + "=";
const ca = document.cookie.split(';');
for (let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) === ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
Purpose: Retrieves cookie values by name
Returns: Cookie value string or null if not found
Technical Details:
- Parses
document.cookiestring (semicolon-delimited) - Handles whitespace trimming around cookie pairs
- Uses string matching to find target cookie
- Returns null for non-existent cookies
2. State Detection & UI Adaptation
Current Implementation
// Check if user has already seen the easter egg modal
const hasSeenEasterEgg = getCookie('seen_easter_egg');
if (!hasSeenEasterEgg) {
// First-time user: Show full modal
setTimeout(function() {
const easterEggModal = new bootstrap.Modal(document.getElementById('easterEggModal'));
easterEggModal.show();
setCookie('seen_easter_egg', 'true', 30); // 30 days
}, 1000);
} else {
// Returning user: Show navigation options
showEggNavigationOptions();
}
Dynamic UI Injection
function showEggNavigationOptions() {
const container = document.getElementById('advancedOptionsContainer');
if (container) {
container.innerHTML = `
<div class="egg-navigation-options">
<button type="button" class="btn btn-primary" onclick="launchEasterEgg()">
<span class="btn-icon">๐ฅ</span> Physics Explorer
</button>
<button type="button" class="btn btn-secondary" onclick="launchEasterEgg2()">
<span class="btn-icon">๐งช</span> Explorer 2
</button>
<button type="button" class="btn btn-secondary" onclick="showAdvancedOptionsTeaser()">
<span class="btn-icon">โ๏ธ</span> Advanced
</button>
</div>
`;
}
}
Cookie Schema
Current Cookie Structure
| Cookie Name | Value | Duration | Purpose |
|---|---|---|---|
seen_easter_egg |
"true" |
30 days | Tracks easter egg modal display |
Cookie Characteristics
- Storage Type: Client-side browser cookies
- Scope: Domain-wide (path="/")
- Security: None (HTTP-only not set, secure flag not set)
- Size: Minimal (~20 bytes per cookie)
- Persistence: Configurable expiration (currently 30 days)
User Flow States
State 1: First-Time User
User triggers condition (filtered data < 3000)
โ getCookie('seen_easter_egg') returns null
โ Show modal with 1-second delay
โ setCookie('seen_easter_egg', 'true', 30) on modal display
โ User interacts with modal
โ State transitions to "Returning User"
State 2: Returning User
User triggers condition (filtered data < 3000)
โ getCookie('seen_easter_egg') returns "true"
โ Skip modal display
โ Execute showEggNavigationOptions()
โ Inject navigation buttons into DOM
โ User has direct access to features
Trigger Conditions
Current Implementation
<?php if (count($filtered_data) < 3000 && count($filtered_data) > 0): ?>
// JavaScript execution context
<?php endif; ?>
Conditions:
- Filtered dataset has more than 0 records
- Filtered dataset has fewer than 3000 records
- User is on the main data explorer page
Technical Considerations
Security
- Current: No security measures implemented
- Vulnerability: Cookies are readable/writable by client-side JavaScript
- Risk: Low (preference tracking only, no sensitive data)
Privacy
- Data Stored: Boolean preference state only
- PII: No personally identifiable information
- Compliance: No special requirements for preference cookies
Performance
- Impact: Minimal (single string comparison per page load)
- Storage: ~20 bytes per tracked state
- Network: No additional HTTP requests
Browser Compatibility
- Support: All modern browsers (IE9+)
- Fallback: Graceful degradation (modal shows every time if cookies disabled)
- Storage Limits: Well within browser cookie limits (4KB per cookie, 20+ cookies per domain)
Expansion Opportunities
Site-Wide Tracking System
Proposed Enhanced Schema
// Centralized tracking object
const userPreferences = {
seen_easter_egg: true,
tutorial_completed: false,
ui_theme: 'dark',
last_visit: '2024-07-06',
feature_flags: {
advanced_filters: true,
physics_viz: true,
export_tools: false
}
};
// Store as JSON string
setCookie('user_preferences', JSON.stringify(userPreferences), 365);
Centralized Management
class UserTracker {
constructor() {
this.cookieName = 'user_preferences';
this.defaultPrefs = {
seen_modals: {},
feature_flags: {},
ui_preferences: {}
};
this.preferences = this.loadPreferences();
}
loadPreferences() {
const cookie = getCookie(this.cookieName);
return cookie ? JSON.parse(cookie) : this.defaultPrefs;
}
savePreferences() {
setCookie(this.cookieName, JSON.stringify(this.preferences), 365);
}
hasSeenModal(modalId) {
return this.preferences.seen_modals[modalId] || false;
}
markModalSeen(modalId) {
this.preferences.seen_modals[modalId] = true;
this.savePreferences();
}
isFeatureEnabled(featureId) {
return this.preferences.feature_flags[featureId] || false;
}
setFeatureFlag(featureId, enabled) {
this.preferences.feature_flags[featureId] = enabled;
this.savePreferences();
}
}
Usage Example
const tracker = new UserTracker();
// Check if user has seen specific modal
if (!tracker.hasSeenModal('easter_egg')) {
showModal('easter_egg');
tracker.markModalSeen('easter_egg');
}
// Feature flag checking
if (tracker.isFeatureEnabled('advanced_search')) {
enableAdvancedSearchUI();
}
Enhanced Features
1. Multi-Modal Tracking
- Track multiple modals independently
- Configure different expiration times per modal
- Support modal prerequisites/sequences
2. Feature Flags
- Enable/disable features based on user progression
- A/B testing capabilities
- Gradual feature rollouts
3. User Journey Analytics
- Track user progression through features
- Measure feature adoption rates
- Identify user behavior patterns
4. Preferences Management
- UI theme preferences
- Default filter settings
- Display preferences
- Accessibility settings
Security Enhancements for Site-Wide Implementation
Recommended Improvements
1. Cookie Security
// Enhanced cookie setting with security flags
function setSecureCookie(name, value, days, secure = true) {
let expires = "";
if (days) {
const date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toUTCString();
}
const secureFlag = secure && location.protocol === 'https:' ? '; Secure' : '';
const sameSiteFlag = '; SameSite=Strict';
document.cookie = name + "=" + (value || "") + expires + "; path=/" + secureFlag + sameSiteFlag;
}
2. Data Validation
function validatePreferences(preferences) {
try {
const parsed = JSON.parse(preferences);
// Validate structure
if (typeof parsed !== 'object') return false;
// Additional validation rules
return true;
} catch (e) {
return false;
}
}
3. Size Management
// Implement size limits to prevent cookie overflow
const MAX_COOKIE_SIZE = 3000; // bytes
function compressPreferences(preferences) {
const compressed = JSON.stringify(preferences);
if (compressed.length > MAX_COOKIE_SIZE) {
// Implement compression or selective storage
return selectiveStorage(preferences);
}
return compressed;
}
Migration Strategy
Phase 1: Current Implementation
- Single-purpose easter egg tracking
- Simple boolean state management
- Basic cookie operations
Phase 2: Enhanced Single-Feature Tracking
- JSON-based storage
- Multiple modal tracking
- Improved error handling
Phase 3: Site-Wide Implementation
- Centralized UserTracker class
- Feature flag system
- Preferences management
Phase 4: Advanced Analytics
- User journey tracking
- Behavior analytics
- A/B testing framework
Testing & Validation
Test Cases
- First Visit: Verify modal shows and cookie is set
- Return Visit: Verify modal is skipped and options appear
- Cookie Expiration: Test behavior after cookie expires
- Disabled Cookies: Verify graceful fallback
- Multiple Sessions: Test persistence across browser sessions
Debugging
// Debug function to inspect current state
function debugTracking() {
console.log('All cookies:', document.cookie);
console.log('Easter egg seen:', getCookie('seen_easter_egg'));
console.log('Local storage available:', typeof(Storage) !== "undefined");
}
Performance Monitoring
Metrics to Track
- Cookie read/write frequency
- UI adaptation response times
- Memory usage of tracking objects
- Browser compatibility issues
Optimization Opportunities
- Lazy loading of tracking functionality
- Selective cookie updates (only write when changed)
- Compression for large preference objects
- Local storage fallback for browsers with cookie limitations
Conclusion
The current cookie tracking implementation provides a solid foundation for user experience management. The system is lightweight, effective, and easily expandable. The modular design allows for incremental enhancement while maintaining backward compatibility.
Key strengths:
- Simple implementation
- Reliable browser support
- Minimal performance impact
- Clear separation of concerns
Recommended next steps:
- Implement enhanced error handling
- Add validation for cookie data
- Create centralized tracking class
- Plan site-wide expansion strategy
This system can serve as the foundation for a comprehensive user experience management platform while maintaining the simplicity and reliability of the current implementation.