Home > Software design >  How do I leave a user logged in after refreshing the page?
How do I leave a user logged in after refreshing the page?

Time:10-22

I am making a mini application with the Auth system. On the backend, I use the NodeJS and JWT token that I put in the Cookie and check it and make protected middleware. It all works great for me, but on the frontend (React) when I log in everything works until I refresh the page, when I refresh it the user is an empty object and my state is reset. How do I keep a logged-in user even after refreshing the page?

This is my React Reducer:

export const userLoginReducer = (state = { user: {} }, action) => {
  switch (action.type) {
    case USER_LOGIN_REQUEST:
      return { loading: true, isAuthenticated: false };
    case USER_LOGIN_SUCCESS:
      return {
        ...state,
        loading: false,
        isAuthenticated: true,
        user: action.payload,
      };
    case USER_LOGIN_FAIL:
      return { loading: false, isAuthenticated: false, error: action.payload };
    case USER_LOGOUT:
      return { loading: false, isAuthenticated: false, user: null };
    default:
      return state;
  }
};

This is my React Action:

const { data } = await API.post(
  '/api/v1/users/login',
  { email, password },
  config
);



 dispatch({
      type: USER_LOGIN_SUCCESS,
      payload: data,
    });
} catch (error) {
    dispatch({
      type: USER_LOGIN_FAIL,
      payload:
        error.response && error.response.data.message
          ? error.response.data.message
          : error.message,
    });
  }
};

API is config for Axios:

export default axios.create({
  baseURL: 'http://localhost:8000',
  withCredentials: true,
  credentials: 'include',
});

And this is my Login Screen:

const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  const redirect = location.search ? location.search.split('=')[1] : '/';

  const dispatch = useDispatch();

  const userLogin = useSelector(state => state.userLogin);
  const { loading, error, isAuthenticated } = userLogin;

  useEffect(() => {
    if (isAuthenticated) {
      history.push(redirect);
    }

    if (error) {
      console.log(error);
    }
  }, [isAuthenticated, history, redirect, error]);

  const submitHandler = e => {
    e.preventDefault();
    dispatch(login(email, password));
  };

I am new into React so if can someone help me i will be happy.

CodePudding user response:

One of available options is providing an additional authorizing endpoint.

  1. User sends request e.g. to /user or /auth right after entering a page
  2. You read cookie on the server and return a decoded (from cookie) user data object
  3. Based on response - you either log user in or you don't (if you found no cookie data or it was forged)

CodePudding user response:

You need to save your user login information on the client-side.

As a solution, you can save the user token, username, id, ... with the browser localStorage and get it when you need them.

But, the proper solution is to use some persistor like redux-persis to save your whole state, or a slice of it to avoid losing information on the redux store after refresh pages. behind the scene, redux-persist, uses the localStorage to save your store object.

More information about the redux-persis and how to implement it is here.

  • Related