DEV Community

Handling Session Updates for Authenticated Users With NextAuth and JWT

Nick on February 04, 2023

NextAuth is hands down the best authentication solution for Nextjs. I've been using it for over a year now and one of the challenges I've faced is...
Collapse
 
designly profile image
Jay @ Designly

Thanks for this, saved me a lot of time! :-)

Collapse
 
fwm profile image
Alex Malikov

This is so mind blowing! So maybe you could answer me, is there a way to access (at least read) data from jwt not putting it into the session? As I understand in v4 there was a getToken function, but in v5 it’s everything done using session. Or no way?

Collapse
 
ali-raza764 profile image
Ali Raza Khalid

if (req.query?.companyId) {
token.selectedCompanyId = req.query.companyId as string
}
For Me It gives an error saying that the req is undefined

Collapse
 
ali-raza764 profile image
Ali Raza Khalid

Even if I wrap the function it produces unexpected results.
Please share full code for our understanding.

Collapse
 
rogercastaneda profile image
Roger Castañeda

Good approach Nick!, what do you recommend to persist some sensitive data like fullName, email, id in the session?

Collapse
 
nick profile image
Nick • Edited

Hi Roger, thank you for the comment!

As I emphasized in the Conclusion of the article, sensitive data - such as passwords and API keys - should NEVER be stored in a session, not even in the token. It's important to store such data in a secure database and encrypt it to protect the user's privacy.

On the other hand, it is generally considered safe to store non-sensitive data such as the user's full name, email, and ID in a session as they don't pose a risk to the user's privacy.