Search code examples
node.jsreactjsauthenticationjwtmern

Is it a good practice to send all the User details stored in DB via JWT token?


I am developing a Demo WebApp using the MERN stack and using JWT for Authentication.

In the Backend, when a user requests to log in, I am preparing a JWT token by adding the MongoDB ObjectID for that user in the token's payload with necessary timestamps.

On User login, I want to store the User details for that session on Frontend. I know that I can share all those details via API response & store it using React Context/ Redux. But is it a good practice to create a JWT token from the backend with all the session-specific User details stored on DB (Apart from secure information) into Payload during login & sending the encrypted token in the response? So that, I can decrypt & destructure the user details from the JWT token and store them for that session.

Eager to know the Pros and Cons of the above process keeping best coding practices into consideration.


Solution

  • It seems like you need something like an ID token from OpenID Connect (https://openid.net/). This is a JWT which contains user data used on the frontend to identify user, maybe print their username somewhere, etc. It is a common practice to use it, but you should remember that if you put too much information into that token it will get quite large (which can have an impact on slower connections, or slower computers which will need to decode it, verify signatures, etc.)

    Another viable option is to have an endpoint which returns all that information when needed (see the userinfo endpoint in OIDC).

    You also have to remember that all that information will be readable to anyone who has access to that JWT, so no personal information should be kept there.

    Just a note - I can decrypt & destructure the user details from the JWT token - you probably mean decode here. Decoding is the act of changing the JWT from a base64 encoded string into a JSON object. You can have truly encrypted JWTs (JWE), which guards them from being read by eavesdroppers, but you wouldn't use them in a frontend app. They are also much more complicated to set up and use more CPU.