Hi all, Can you please share the exact snippet of code or a sample code for the server side tracking of the equivalence of a page viewed event on the CS where a user sends a request and the trigger is the server receiving the request for specific URLs? kapa.ai
Certainly! I can provide you with a sample code snippet for server-side tracking of a page view event in Python. This example assumes you're using a web framework like Flask or Django. Here's a code snippet that demonstrates how to track a "Page Viewed" event when the server receives a request for specific URLs:```from mixpanel import Mixpanel from urllib.parse import urlparse# Initialize Mixpanel client mp = Mixpanel("YOUR_PROJECT_TOKEN")def track_page_view(request): # Extract the URL from the request url = request.url # This may vary depending on your web framework # Define the specific URLs you want to track tracked_urls = ['/home', '/products', '/about'] # Check if the current URL path is in the list of tracked URLs if urlparse(url).path in tracked_urls: # Prepare event properties properties = { "Page URL": url, "referrer": request.headers["Referer"], "$referring_domain": urlparse(request.headers["Referer"]).hostname }) # Set the user's IP address for accurate geolocation properties["ip"] = request.remote_addr # Track the "Page Viewed" event mp.track(request.user_id, "Page Viewed", properties)# Use this function in your route handler def handle_request(request): # Your existing request handling logic here
# Track the page view
track_page_view(request)
# Continue with your response logic
# ...LBKS```LBKSLBKSThis code snippet does the following:LBKS1. It initializes the Mixpanel client with your project token.
2. The track_page_view
function is called when a request is received.
3. It checks if the requested URL path is in a list of specific URLs you want to track.
4. If the URL is tracked, it prepares event properties including the full URL.
5. It adds UTM parameters and referrer information if available.
6. It sets the user's IP address for accurate geolocation.
7. Finally, it tracks a "Page Viewed" event with all the collected properties.Remember to replace "YOUR_PROJECT_TOKEN"
with your actual Mixpanel project token.This example provides a basic structure for server-side page view tracking. You may need to adjust it based on your specific web framework and requirements.Mixpanel SDKs: Python
Server-Side Best Practices
kapa.ai is still learning and improving, please let me know how I did by reacting below.
ℹ️ Tip: Mention @kapa.ai in the thread for follow-ups or DM the app for 1-to-1 help.