How do I keep track of whether the user is logged in on my website or not?

I am new to React and have tried to find an answer for this. Maybe I am looking for the wrong thing.

But I am currently using an API on my React site which returns an access token after I have logged in. I keep track of whether or not the user is logged in by whether or not there exists an access token. The problem is if I were to go to another page or return to it, the access token and the API wrapper will be wiped. I would have to log in again and reretrieve all of my data.

Is there some way I can store either my data (maybe through Express)? Thank you

3 answers

  • answered 2020-06-27 04:04 Hyetigran

    It sounds like you're using JWT for auth. You'll want to save your token in localStorage when signing in

    .then(response => {
          const { token, userId } = response.data;
          localStorage.setItem("token", token);
          localStorage.setItem("userId", userId);
    

    Then set certain routes as Private that require a token for access

    <Switch>
                <Route exact path="/" render={props => <Home {...props} />} />
                <Route path="/login" render={props => <Login {...props} />} />
                <Route path="/signup" render={props => <Signup {...props} />} />
                <PrivateRoute
                  path="/account"
                  render={props => <Account {...props} />}
                />
                <PrivateRoute
                  path="/dashboard"
                  render={props => <Dashboard {...props} />}
                />
    </Switch>
    

    PrivateRoute Component

    import React from "react";
    import { Route, Redirect } from "react-router-dom";
    
    const PrivateRoute = ({ render: Component, ...rest }) => {
      return (
        <Route
          {...rest}
          render={props => {
            if (localStorage.getItem("token")) {
              return <Component {...props} />;
            } else {
              return <Redirect to="/" />;
            }
          }}
        />
      );
    };
    
    export default PrivateRoute;
    

  • answered 2020-06-27 04:06 Pedro Wanderley

    You can save the token in the browsers storage.

    If you’re using redux, consider use redux persist also.

  • answered 2020-06-27 04:54 Nikhil Adiga

    The usual way while using JWT would be to store the token in local storage and make the API call to authenticate that token in componentDidMount() lifecycle of App.js component so that you don't get logged out on browser refresh. The token expiring time should be handled in the backend