I'm trying to initialize a session in my website once a user logs in, but for some reason, once a user successfully logs in, a cookie isn't sent to the browser and a session isn't maintained. When I tried playing with the website's API in Postman, a session was successfully maintained, but in Google browser it isn't.
This is my code for initializing a session:
const express = require('express');
const app = express();
const dotenv = require('dotenv').config();
const session = require('express-session');
const store = session.MemoryStore();
const helmet = require('helmet');
const cors = require('cors');
const cookieParser = require('cookie-parser');
app.enable("trust proxy");
app.use(cookieParser());
app.use(helmet());
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(session({
resave: false,
saveUninitialized: true,
secret: process.env.SESSION_SECRET,
cookie: {maxAge: 1000*60*60, sameSite: 'none', secure: false},
store,
}));
Once a user successfully logs in, a 'user' property and an 'authenticated' property get attached to the session object, and for any subsequent request, the server checks if the client is authenticated with the following function:
const checkIfAuthenticated = (req, res, next) => {
if(req.session.authenticated){
next();
} else {
res.json("Please authenticate yourself!");
};
};
After a user successfully logs in , a session should successfully be maintained. What actually happens is that once a user logs in successfully and tries to access and modify personal data, they are sent "Please authenticate yourself!", meaning that no session was initialized.
This is my frontend code for logging in (a username and a password re needed):
export async function loginUser(username, password){
console.log(username, password);
const res = await fetch('http://localhost:4001/login', {
method: 'POST',
body: JSON.stringify({username, password}),
headers: {
"Content-Type": "application/json",
},
});
const jsonRes = await res.json();
return jsonRes;
}
And this is my frontend code for fetching products data (Any request to the products data is first authenticated by the 'checkIfAuthenticated' function written above, and if the user is authenticated, the server sends the products, and if not, the user will be asked to authenticate themself):
export async function getAllProducts(){
const products = await fetch('http://localhost:4001/products');
const jsonProducts = await products.json();
return jsonProducts;
}
What should I change in my code in order for it to work properly?