I'm writing a mern application that uses passport-local as the authentication strategy on the backend. Essentially, when a user logs in on the frontend, the Login component takes the data submitted, (username, password) and a post request is made by axios to the backend, which runs this code.
export const loginUser: RequestHandler = async (req, res, next) => {
passport.authenticate("local", (err, user, info) => {
if (err) throw err;
if (!user) return res.redirect("/login");
req.login(user, (err) => {
if (err) throw err;
const user: IUser = req.user as IUser;
const userResponse: IUserResponse = {
id: user.id.toString(),
username: user.username,
active: user.active,
deleted: user.deleted,
role: user.role,
};
return res.status(200).json({ user: userResponse });
});
})(req, res, next);
};
this code is run.
As you can see, a json response object with the user is sent back. Additionally, when this occurs, a session is initialized that can be viewed under the application tab of chrome. It looks something like:
connect.sid | s%3ASA6H5MmRMehW-R-SBRya18fGpOmCBAZT.%2BGVd6WRe853RsjY6iaOZrYzizQrQJx2A7Ow5u48QfMw | localhost | / | Session | 93 | httpOnly | Medium
I know this is the session id. When a user logs in, the redux state is updated to reflect that the user is authenticated, however, when the user refreshes the page, the state is cleared and they are no longer authenticated. However, the session id remains.
What is the best way to persist this auth-state?
Questions I have looked at thoroughly before anyone marks this as a duplicate:
How to store authentication state in react and express app
Gives a nice framework but no real implementation ideas.
On React Router, how to stay logged in state even page refresh?
I'm not using JWT auth, I'm using passport-local.
How to persist login after refresh in react-redux app using JWT
Again, JWT based. I've used JWTs before. I'm trying to use passport in this case.
I've also looked at several medium articles and youtube videos since 7AM this morning trying to solve this and what I've gathered so far is this:
- use localstorage somehow
- use the session somehow
I really am at a roadblock, so any help would be very much appreciated. Please ask for information if I have not provided it.
As always, if you answer or attempt to answer this question, thank you for your time.