sunny tran
sunny tran

Reputation: 15

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 till now I am looking for the wrong thing.

I am currently using an API on my React site which returns an access token after user have logged in.

I keep track of the user is logged in or not by checking whether or not access token exists for that user.

The problem is if I navigate to another page or return to it, the access token and the API wrapper will be wiped.

I have to log in again and retrieve all of my data. (repeat the login process)

Is there some way I can store my data (maybe through Express)? or any other recommended way.

Thank you

Upvotes: 1

Views: 2037

Answers (3)

Nikhil Adiga
Nikhil Adiga

Reputation: 150

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

Upvotes: 2

Pedro Wanderley
Pedro Wanderley

Reputation: 23

You can save the token in the browsers storage.

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

Upvotes: 0

Hyetigran
Hyetigran

Reputation: 1215

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;

Upvotes: 0

Related Questions