Search code examples
reactjsjwtexpress-jwt

Client Side authentication with ReactJs


I'm still learning full-stack Development and I'm following this tutorial to create the API but I can't wrap my head around authentication on the client-side. So I'm using ReactJs in the frontend and I can't figure out how to keep track of a logged-in user(to show his name and his profile picture on the navbar for example). I've read about storing the logged-in user in the localStorage and how it's not secure enough. this is the code for creating a new user and logging him in. I'm using ExpressJs and JWT

const createSendToken = (user, statusCode, res) => {
const token = signToken(user.id);
res.cookie("jwt", token, {
expires: new Date(
  Date.now() + 90 * 24 * 60 * 60 * 1000
),
secure: true,
httpOnly: true,
});
user.password=undefined;
res.status(statusCode).json({
status: "success",
token,
data: {
  user,
},
});
};
exports.signup = async (req, res, next) => {
const newUser = await User.create({
name: req.body.name,
email: req.body.email,
password: req.body.password,
passwordConfirm: req.body.passwordConfirm,
});
createSendToken(newUser, 201, res);
};

Solution

  • You can store the token in state and ask your api for a refresh token everytime you get a jwt expired error