I’m a huge fan of Flask, the Python framework, a great way to easily start and scale web apps.
You can have a basic app up and running in a few minutes.
And I’m also a huge fan of PostHog, one of the best and most affordable user-centric analytics tools on the market. It it so elegant!
You can easily set it up in your web app by adding a JS snippet into the <head> section of your site.
It will auto-capture all events by default, incl. the text of the clicked buttons, which makes it very easy to get insights for specific conversion funnels.
But what if you want to identify the logged-in users in your PostHog events explorer?
You’ll need to add some javascript to your app JS file.
This is basically the code I run when someone opens the AI Jinglemaker after signing up.
Important: I’ve added the following line after a recent update of PostHog’s JS SDK:
let userIdString = String(data.user_id);
PostHog used to accept integers as userId but it’s not the case anymore so you have to convert any id to a String, otherwise you’ll see this type of error in your JS console (e.toLowerCase is not a function):
logger.ts:39 [PostHog.js] Implementation error. Please turn on debug and contact [email protected].
critical @ logger.ts:39
(anonymous) @ index.ts:184
(anonymous) @ app.obs.js:1
Promise.then (async)
(anonymous) @ app.obs.js:1
logger.ts:39 [PostHog.js] TypeError: e.toLowerCase is not a function
at e.value (index.ts:492:57)
at e.<anonymous> (index.ts:182:22)
let userId = null;
fetch('/get_current_user_data')
.then(response => response.json())
.then(data => {
// Convert user_id to a string if it's not already
let userIdString = String(data.user_id);
// Use the PostHog JS library to identify the user
posthog.identify(
userIdString,
{ email: data.email }
);
// Save the user_id for later use
userId = data.user_id;
}
})
.catch(error => {
console.error('Error fetching user data:', error);
});
As you can see my JS code calls a dedicated route in my Flask backend (get_current_user_data).
What this route does is very simple, here’s the Python code.
@app.route('/get_current_user_data')
@login_required
def get_current_user_data():
user_id = current_user.id
db = get_db()
cursor = db.cursor()
cursor.execute('SELECT * FROM users WHERE id=%s', (user_id,))
result = cursor.fetchone()
user_email = result[2]
# Return as JSON
return jsonify({
'user_id': user_id,
'email': user_email
})
It first gets the id of the current_user (leveraging Flask’s built-in authentication features).
Then it connects to the users table in my MySQL DB and searches for this user id to get the email of the user, which it then pushes backs to the client in JSON format.
In the JS code, I then declare the email for PostHog and we save the userId which we’ll use elsewhere in the JS for various purposes.
That’s how easy it is to identify logged-in users in PostHog via Flask/Python and Javascript.
If you have any questions, don’t hesitate to contact me.