0

I am new to React but somehow I have managed to develop a MERN (Mongoose, Express, React, Node) app. The back-end stores the data into the Mongo database. It sends and receives API to the front-end with the user data. I am receiving user data from the back-end who have already registered and storing it into a global hook so that it can be shared by all the components.

What I want to achieve is to be able to render components based on whether the user is logged in or not. I need something like JWT with local storage or a cookie but not sure how to start. The user information should presists even when the app is refreshed. Can someone suggest how I can achieve this?

Also, I am using react-router-dom ^6. I have realized that there are some differences in the previous versions.

Thanks in advance!

  • How're you handling the logins in your app right now? It would make sense to store if the user has authenticated to local storage and then use that when the app loads. Something like this https://stackoverflow.com/questions/31084779/how-to-restrict-access-to-routes-in-react-router/42708437#42708437 – jayair Nov 27 '20 at 20:43

1 Answers1

0

There is more than one right answer to this question. Typically you will send a JWT token to the front-end and store that in your local storage. Than you check your local storage and give the user access to you defined auth routes.

If you want to take it a step further. You can send two tokens a normal JWT token and a JWT refresh token with an expiry time (typically 15min). That refresh token is attached to every request and updated on the backend. The front end is consistently checking if the token is still valid inside a useEffect function. Both tokens are stored on your local storage, while the main token is used keep the user logged in. If the refresh token expires the main token and refresh token get deleted and the user is logged out.

If you want to take it another step further you can use redis to store the JWT token on the backend and check on every request on the backend if the token is still valid based on the userId.

However, you can also use cookies. I recommend using the refresh token approach since it seems to be the most common approach.

Noah Kanyo
  • 500
  • 1
  • 3
  • 8