I have a seprate backend and frontend. Frontend in in next and backend is in express. I am trying to setup auth like this.
const session = require('express-session');
const cookieParser = require('cookie-parser');
// Middleware
require('dotenv').config();
app.use(morgan('tiny'));
app.use(bodyParser.json());
app.use(cors());
app.use(
session({
secret: process.env.SECRET,
resave: false,
saveUninitialized: false,
cookie: { maxAge: 24 * 60 * 60 * 1000 }, // 24 hours
})
);
app.use(cookieParser());
I am checking auth with a middleware which looks like this :
// Checks logged in or not
module.exports.isLoggedIn = (req, res, next) => {
if (req.session.userId) {
next();
} else {
res.status(401).json({ message: "Unauthorized" });
}
};
In React I am using axios to login
const handleSubmit = async (event) => {
event.preventDefault();
// Perform form submission or further processing with formData
try {
const response = await axios.post(
'http://localhost:5000/auth/login',
formData
);
console.log(response.data);
setFormData({
email: '',
password: '',
});
} catch (e) {
console.log(e);
}
};
The login is being executed successfully. But session is not being stored. When I try to fetch resources after login it is throwing me 401.