I am creating a web application with a rest api in expressjs and the frontend in reactjs. I would like to have access to the user information on my react app as well as know if the user is logged in without api calls. How do big apps solve this problem?
CodePudding user response:
I would like to have access to user information in my React app as well as know if the user is logged-in without api calls.
At one point or another, you will need to make calls to your API in order for React to retrieve the information it needs.
Now, whether or not you need to make that request just once or on every route change is entirely dependent on the functionality of your application.
Generally, the way "big apps" approach this is with the use of sessions. A session will store a cookie string on the user's front end, which will be attached to a user's logged-in state (true
or false
).
So, whenever you need to fetch sensitive data or protect a certain page from invalidated users, you would send this string along with a request to validate on your back end (via the API).
A generic flow might look something like this:
- The user logs in on the front end.
- Their credentials are validated on the backend (via your API), and a session token is returned.
- The session token is stored on the front end as a cookie.
- The user attempts to access or retrieve some sensitive information via the API.
- The session token will be sent In the request headers to be validated in the back end.
- Once validated, the appropriate information is returned from the API.
Obviously, this is a quite simplified explanation of everything, so I would heavily suggest you take a poke around about sessions and the handling of user data.
Good luck!
CodePudding user response:
Like GROVER. said, you have to make at least one API call to fetch the data
About the cookie validation part, JWT could be handy, it contains 3 parts separated by dots (.):
- Header (type of token and signing algorithm)
- Payload (expiration, your data, issuer, ...)
- Signature (encoded with secret string; for validation in the backend later)
You can set payload in the express.js and then in the frontend you can parse data, then you can only check JWT "offline" in the frontend (for example check only expiration time in the payload, or just parse data from the payload without any validation, but I would not highly recommend this to you because of security) or validate token with an API call to your backend (because your secret should be only in the backend)