In my React app I have some protected pages, and this useEffect hook runs when one of them is loaded.
useEffect(() => {
axios
.get("http://localhost:3000/dashboard")
.then((res) => {
if (res.status === 401) {
navigate("/login");
}
})
.catch((err) => console.log(err));
});
My server sets sessions and checks if the user is logged in with this logic:
// app.js session logic
app.use(cookieParser());
app.use(
session({
name: "Sid",
secret: "badSecret",
saveUninitialized: true,
resave: false,
store: // mongodb connection
cookie: {
maxAge: 60000,
},
})
);
app.use(authRoutes);
// authRoutes middleware for creating and authenticating sessions
redirectToLogin: (req, res, next) => {
if (!req.session.user) {
res.status(401);
} else {
next();
}
},
login: (req, res) => {
// this only runs if it's successful
// user is the user object from the database
const sessionData = {
email: user.email,
};
req.session.user = sessionData;
res.status(200).send(req.session.sessionId);
};
A user property is only added to the session if the user logged in successfully. This is why I check if the property exists in the redirect function, and if it does't, the server returns a 401 unauthorized response. However, my hook isn't doing anything, and it doesn't look like req.session.user is adding anything.
When I check on the server, the if statement is entered all the time, but when I check on the client, no response is being logged. I tried logging the req.session.user object, but it return undefined. It is in the database stored outside the cookie.
What could cause req.session to not be storing any data?