Question:
I am fetching user data from graphql backend through apollo client. My goal is to keep the user logged in so I signed jwt token with all user data, passed it to localStorage(only the token) decoded it and passed all values to redux-store.Answer:
it’s not recommended (actually very dangerous) to return all information with the jwt token especially password. I think userId is enough! But you can also return username, firstName, lastName, etc. But in some cases even returning email address is not a good approach for some user privacy reasons.I mean by that you have only to get the userId once there is a user and the credentials are correct, then :
Now after signing the jwt token , you can set whatever data from user inside some redux state or even react context , (choose your favorite) , but DON’T set any password in the localStorage.
Update: at the end you should store the user from the payload like this :
Btw you should check the localStorage only to get the token and verify it , then based on userId you need to fetch the user and store it, here is an example :
const getUser = React.useCallback(async (userId) => {
try {
const res = await axios.post(‘/auth/login’, {userId}, {
credentials: ‘include’,
withCredentials: true
});
const { accessToken, user } = res.data;
setState((currentState: IState) => ({
…currentState,
user,
loading: false,
isAuth: !!accessToken,
accessToken
}));
} catch (err) {
setState((currentState: IState) => ({
…currentState,
user: null,
loading: false,
isAuth: false,
accessToken: ”
}));
}
}, []);
useEffect(() => {
getUser(userId);
}, [getUser]);
useEffect(() => {
const jwtToken = localStorage.getItem(‘jwtToken’);
if (jwtToken && jwt_decode(jwtToken)) {
const { exp } = jwt_decode(jwtToken);
const currentTime = Date.now() / 1000;
if (exp < currentTime) {
getUserById(userId);
}
}
}, [getUser]);[/code]
If you have better answer, please add a comment about this, thank you!