How can i reproduce device_id in server side integration?
Hi Michael L., Please stand by as I search the Mixpanel knowledge base for an AI-powered answer. I normally take about 15 seconds or so. In case AI cannot answer your question, feel free to reach out to Mixpanel support at mixpanel.com/get-support. If you have follow-up questions for this thread, please tag me again with your question: @kapa.ai <follow-up question> đź‘‹
Feel free to ask a follow-up question once I've answered by mentioning me with @kapa.ai
To reproduce $device_id
in a server-side integration with Mixpanel, you need to generate and manage these IDs yourself, as Mixpanel's server-side libraries don't automatically generate them like the client-side SDKs do. Here's how you can approach this:
Step 1: Generate an Anonymous ID
Generate a unique identifier (preferably a UUID) for each user session and store it in a cookie or other persistent storage mechanism: ```import uuid
Generate a unique ID
anonymous_id = str(uuid.uuid4())
Store this in a cookie or session
Step 2: Use this ID as the $device_id in your events
When tracking events, include this ID as the $device_id
property: ```
Example in pseudocode
def track_to_mp(request, event_name, properties):
Get the anonymous ID from cookie
properties["$device_id"] = request.cookies.get('SESSION_ID')
If user is authenticated, also include $user_id
if request.user.is_authenticated(): properties["$user_id"] = request.user.username
Send to Mixpanel
mp.track("", event_name, properties)```
Best Practices
- For projects using Simplified ID Merge API, you should set both $device_id
(for anonymous state) and $user_id
(when identified) in your events. This allows Mixpanel to automatically merge user identities.
- For projects using Original ID Merge API, you'll need to explicitly send an $identify
event to merge anonymous and identified users.
- Ensure consistency in how you generate and manage these IDs across your server infrastructure.Identifying Users (Simplified) provides more details on server-side identity management for Simplified ID Merge projects.Remember that the implementation will vary slightly depending on your server framework and which ID Merge system your Mixpanel project is using.
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.