adriam
adriam

Reputation: 451

How to check if a user is logged in and how to save their information? (React)

So pretty much I made a login page communicates with a backend to login a user. Now I want to take their data and store it for all my other components to know that there is

  1. A user logged in
  2. Have access to the user's information

I figured based on past StackOverflow answers, that the best way to do this is using JWT and LocalStorage. But all the answer's I've encountered seem to use Redux. I'm not using Redux at all for my application, and have no clue how to use it, so I was wondering if there's a way to do it without redux.

Upvotes: 12

Views: 24710

Answers (1)

Tiago Alves
Tiago Alves

Reputation: 2316

You don't need Redux. You just have to store the JWT in localStorage. To do that, just use localStorage.setItem('token', data.token) when you receive the login success response from the API. It's that simple. You can read this article for more details. It's for React Redux applications but doesn't need Redux.

Then, assuming you are using react-router, you need two helper functions. The first will go on your protected routes and would look like this:

const requireAuth = (...) => {
  if(!localStorage.getItem('token')) {
    // go to login route
  }
  // stay on this route since the user is authenticated
}

The second goes on your unprotected routes and looks like this:

const verifyAuth = (...) => {
  if(localStorage.getItem('token')) {
    // go to your dashboard or home route
  }
  // stay on this route since the user is not authenticated
}

Keep in mind that you have to refresh the token according to the server expiration time. A good approach would be to create a call to the server asking if the token is still valid.

Upvotes: 18

Related Questions