Next.js Discord

Discord Forum

Help with tracking user session

Unanswered
Sloth bear posted this in #help-forum
Open in Discord
Avatar
Sloth bearOP
I'm working on a project with next.js and prisma (PostgreSQL), for authentication I use (NEXTAUTH),

I just want to know how to track a user's session (Its duration - start and end time each time he enters site)

and this is because i want to calculate the DAU (Daily active users), and other purposes, if anybody gives me ideas i'd be so thankful.

thanks in advance.

7 Replies

Avatar
you can add custom parameters to your next-auth session. When you create the session get the current time and put that current time inside the session. Thats your startTime. Now you can check inside your middleware the session, get the value and compare it with the current time. Like that you got a "endTime" (not really, but you get the point). If you substract it from each other you can get the duration.

At the end you have: startTime, endTime and duration
Avatar
Sloth bearOP
but i will struggle with advanced cases, for example. what if the user logs into the website, then his PC sleeps ? it won't never end, i should then specify what is the endtime (browser closed - logout - network disconnection, etc...)
Avatar
the session itself already have a expires value in it. So if the user leaves his PC it will be expire after the expires time. Depending on your auth method (session or JWT) you might be able to do other stuff as well
Avatar
Sloth bearOP
its actaully JWT,

please do you have ressources that can help me ? i didnt find this on documentation.
Avatar
log your session clientside. You can see an user object and the authenticaed state and (what I mentioned) the expires date
Avatar
@Sloth bear I would recommend you to integrate analytics tools like GA, Log Rocket or MixPanel ...
Avatar