Magenta Analytics Installation Guide
Magenta is a privacy-focused, first-party analytics system that can be installed on any website. Choose between a simple universal installation or a deep Django integration.
Table of Contents
- Universal Installation (Any Website)
- Django Deep Integration
- WordPress Plugin
- React/Vue/Angular
- Advanced Configuration
- Testing & Verification
- Troubleshooting
Universal Installation (Any Website)
The simplest way to add Magenta to any website. Works with static sites, WordPress, Shopify, or any CMS.
Basic Installation
Add this code just before the closing </body>
tag on every page:
<!-- Magenta Analytics -->
<script>
(function() {
// Configuration
window._magenta = {
siteId: 'YOUR_SITE_ID', // Replace with your site ID
apiEndpoint: 'https://magenta.comma.cm/api/v1/analytics/track/'
};
// Load Magenta
var script = document.createElement('script');
script.src = 'https://magenta.comma.cm/magenta.min.js';
script.async = true;
document.head.appendChild(script);
})();
</script>
Single Pixel Image (No JavaScript)
For maximum compatibility or when JavaScript is not available, use the pixel image:
<!-- Magenta Pixel Tracker -->
<img src="https://magenta.comma.cm/pixel.gif?site=YOUR_SITE_ID&page=home"
alt=""
width="1"
height="1"
style="display:none" />
Advanced Pixel with Dynamic Data
<!-- Magenta Dynamic Pixel -->
<img src="https://magenta.comma.cm/pixel.gif?site=YOUR_SITE_ID&page=<?php echo urlencode($_SERVER['REQUEST_URI']); ?>&ref=<?php echo urlencode($_SERVER['HTTP_REFERER']); ?>"
alt=""
width="1"
height="1"
style="display:none" />
Tracking Custom Events
<script>
// Track a custom event
function trackEvent(eventName, properties) {
if (window.magenta && window.magenta.track) {
window.magenta.track(eventName, properties);
}
}
// Example: Track button click
document.getElementById('purchase-button').addEventListener('click', function() {
trackEvent('button_click', {
button: 'purchase',
value: 99.99,
currency: 'USD'
});
});
</script>
User Identification
<script>
// Identify logged-in users
if (window.magenta && window.magenta.identify) {
window.magenta.identify('USER_ID', {
email: 'user@example.com',
plan: 'premium',
created: '2024-01-15'
});
}
</script>
Django Deep Integration
For Django sites, Magenta can be deeply integrated as a first-party analytics solution with server-side rendering and enhanced privacy features.
1. Install Magenta Django App
# Add to your requirements.txt or pyproject.toml
magenta-analytics==1.0.0
# Or install directly
pip install magenta-analytics
2. Add to Django Settings
# settings.py
INSTALLED_APPS = [
# ... your other apps
'magenta_analytics',
]
MIDDLEWARE = [
# ... your other middleware
'magenta_analytics.middleware.MagentaTrackingMiddleware',
]
# Magenta Configuration
MAGENTA_CONFIG = {
'SITE_ID': 'your-site-id',
'API_ENDPOINT': 'https://magenta.comma.cm/api/v1/analytics/track/',
'SERVE_PIXEL': True, # Serve pixel from your domain
'TRACK_AJAX': True, # Track AJAX requests
'TRACK_STAFF': False, # Don't track staff users
'RESPECT_DNT': True, # Respect Do Not Track
'COOKIE_DOMAIN': '.yoursite.com', # For subdomains
}
3. Add URLs
# urls.py
from django.urls import path, include
urlpatterns = [
# ... your other patterns
path('analytics/', include('magenta_analytics.urls')),
]
4. Template Integration
Base Template Setup
{# base.html #}
{% load magenta_tags %}
<!DOCTYPE html>
<html>
<head>
{% magenta_head %}
{# Injects Magenta configuration and styles #}
</head>
<body>
{% magenta_body %}
{# Injects Magenta script with first-party serving #}
{# Your content #}
{% magenta_noscript %}
{# Fallback pixel for users without JavaScript #}
</body>
</html>
Track Specific Pages
{# product_detail.html #}
{% load magenta_tags %}
{% magenta_track_page "product_view" %}
{% magenta_set_property "product_id" product.id %}
{% magenta_set_property "product_name" product.name %}
{% magenta_set_property "price" product.price %}
5. Server-Side Tracking
# views.py
from magenta_analytics import track_event
def purchase_complete(request, order_id):
order = Order.objects.get(id=order_id)
# Track server-side event
track_event(
request=request,
event_name='purchase',
properties={
'order_id': order.id,
'amount': float(order.total),
'items': order.items.count(),
'customer_id': order.customer.id,
}
)
return render(request, 'purchase_complete.html', {'order': order})
6. User Identification
# After login
from magenta_analytics import identify_user
def login_view(request):
# ... handle login
if user.is_authenticated:
identify_user(
request=request,
user_id=user.id,
traits={
'email': user.email,
'name': user.get_full_name(),
'plan': user.subscription.plan,
'created': user.date_joined.isoformat(),
}
)
7. First-Party Pixel Serving
With Django integration, the pixel is served from your domain for better privacy:
{# Automatically generates first-party pixel URL #}
{% magenta_pixel %}
{# Renders as: #}
<img src="/analytics/pixel.gif?s=abc123&p=home" width="1" height="1" alt="" />
8. Custom Middleware for Enhanced Tracking
# myapp/middleware.py
from magenta_analytics.middleware import MagentaTrackingMiddleware
class CustomMagentaMiddleware(MagentaTrackingMiddleware):
def get_custom_properties(self, request):
"""Add custom properties to every event"""
return {
'user_type': 'member' if request.user.is_authenticated else 'visitor',
'device_type': self.get_device_type(request),
'experiment_group': request.session.get('experiment_group', 'control'),
}
def should_track(self, request):
"""Custom logic for when to track"""
# Don't track admin pages
if request.path.startswith('/admin/'):
return False
# Don't track API calls
if request.path.startswith('/api/'):
return False
return super().should_track(request)
9. Management Commands
# Verify installation
python manage.py magenta_verify
# Test tracking
python manage.py magenta_test_track
# Export analytics data
python manage.py magenta_export --start 2024-01-01 --end 2024-01-31
WordPress Plugin
For WordPress sites, install the Magenta plugin:
// wp-content/plugins/magenta-analytics/magenta-analytics.php
<?php
/**
* Plugin Name: Magenta Analytics
* Description: First-party analytics with Magenta
* Version: 1.0.0
*/
// Add tracking code to footer
add_action('wp_footer', 'magenta_tracking_code');
function magenta_tracking_code() {
$site_id = get_option('magenta_site_id', 'wordpress-site');
?>
<!-- Magenta Analytics -->
<script>
window._magenta = {
siteId: '<?php echo esc_js($site_id); ?>',
apiEndpoint: 'https://magenta.comma.cm/api/v1/analytics/track/'
};
</script>
<script src="https://magenta.comma.cm/magenta.min.js" async></script>
<!-- Magenta Pixel Fallback -->
<noscript>
<img src="https://magenta.comma.cm/pixel.gif?site=<?php echo urlencode($site_id); ?>&page=<?php echo urlencode($_SERVER['REQUEST_URI']); ?>"
width="1" height="1" alt="" />
</noscript>
<?php
}
// Track logged-in users
add_action('wp_login', 'magenta_identify_user', 10, 2);
function magenta_identify_user($user_login, $user) {
?>
<script>
if (window.magenta && window.magenta.identify) {
window.magenta.identify('<?php echo $user->ID; ?>', {
email: '<?php echo esc_js($user->user_email); ?>',
username: '<?php echo esc_js($user_login); ?>'
});
}
</script>
<?php
}
SPA Frameworks
React
// MagentaProvider.jsx
import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
export function MagentaProvider({ children, siteId }) {
const location = useLocation();
useEffect(() => {
// Load Magenta
window._magenta = {
siteId: siteId,
apiEndpoint: 'https://magenta.comma.cm/api/v1/analytics/track/'
};
const script = document.createElement('script');
script.src = 'https://magenta.comma.cm/magenta.min.js';
script.async = true;
document.head.appendChild(script);
}, [siteId]);
useEffect(() => {
// Track page views on route change
if (window.magenta && window.magenta.track) {
window.magenta.track('pageview', {
path: location.pathname,
search: location.search
});
}
}, [location]);
return children;
}
// App.jsx
function App() {
return (
<MagentaProvider siteId="react-app">
<Router>
{/* Your routes */}
</Router>
</MagentaProvider>
);
}
Vue.js
// plugins/magenta.js
export default {
install(app, options) {
// Configure Magenta
window._magenta = {
siteId: options.siteId,
apiEndpoint: 'https://magenta.comma.cm/api/v1/analytics/track/'
};
// Load script
const script = document.createElement('script');
script.src = 'https://magenta.comma.cm/magenta.min.js';
script.async = true;
document.head.appendChild(script);
// Add global method
app.config.globalProperties.$track = (event, properties) => {
if (window.magenta && window.magenta.track) {
window.magenta.track(event, properties);
}
};
// Track route changes
app.mixin({
watch: {
$route(to) {
this.$track('pageview', {
path: to.path,
name: to.name
});
}
}
});
}
};
// main.js
import { createApp } from 'vue';
import MagentaPlugin from './plugins/magenta';
const app = createApp(App);
app.use(MagentaPlugin, { siteId: 'vue-app' });
Advanced Configuration
Custom Events
// E-commerce tracking
magenta.track('add_to_cart', {
product_id: '12345',
product_name: 'Premium Subscription',
price: 99.99,
currency: 'USD',
quantity: 1
});
// Form tracking
magenta.track('form_submit', {
form_id: 'newsletter',
form_name: 'Newsletter Signup',
success: true
});
// Video tracking
magenta.track('video_play', {
video_id: 'intro-video',
video_title: 'Product Introduction',
duration: 120
});
Privacy Controls
// Respect user preferences
if (userConsent.analytics) {
window._magenta = {
siteId: 'your-site',
apiEndpoint: 'https://magenta.comma.cm/api/v1/analytics/track/',
respectDoNotTrack: true,
cookieless: userConsent.cookies === false
};
}
// Opt-out mechanism
function optOutOfTracking() {
if (window.magenta && window.magenta.optOut) {
window.magenta.optOut();
}
localStorage.setItem('magenta_opt_out', 'true');
}
Custom Domains
// Use your own domain for analytics
window._magenta = {
siteId: 'your-site',
apiEndpoint: 'https://analytics.yourdomain.com/track/',
scriptUrl: 'https://cdn.yourdomain.com/magenta.js'
};
Testing & Verification
1. Check Installation
Open browser console and type:
window.magenta
// Should return: {track: ƒ, identify: ƒ, ready: true}
2. Verify Tracking
// Test event tracking
magenta.track('test_event', { test: true });
// Check Network tab for request to /track/
3. Debug Mode
window._magenta = {
siteId: 'your-site',
debug: true // Enables console logging
};
4. Browser Extension
Install the Magenta Debugger extension to see events in real-time:
- Chrome: Magenta Analytics Debugger
- Firefox: Magenta Analytics Debugger
Troubleshooting
Events Not Tracking
Check Console Errors
// Look for errors in browser console // Common: CORS, 404, or network errors
Verify Site ID
console.log(window._magenta.siteId); // Should match your registered site ID
Check Network Requests
- Open Network tab
- Filter by "track" or "pixel"
- Verify 200 status code
CORS Issues
Add your domain to Magenta's allowed origins:
Contact support@comma.cm with your domain
Or use first-party serving with Django integration.
Ad Blockers
Some ad blockers may block analytics. Solutions:
- Use first-party domain
- Rename endpoints
- Use server-side tracking
Performance Impact
Magenta is designed to have minimal impact:
- 5KB script (gzipped)
- Async loading
- Batched events
- Local caching
Support
- Documentation: docs.comma.cm/magenta
- Email: magenta@comma.cm
- GitHub: github.com/commau/magenta