I'm using passport.js in a PERN app but when I make get requests the client seems to be generating a new, random session ID with each request. Passport is configured to process the session ID provided to authenticate each request, but obviously that's not working because each random new session ID fails to match the id stored in the database session table.
Get request (front end):
export const welcomeDetails = async () => {
console.log('welcome details called');
try {
const response = await fetch(`${API_ENDPOINT}/welcome`, {
method: "GET",
credentials: 'same-origin',
mode: 'cors',
"Access-Control-Allow-Credentials": true,
headers: {
"Content-Type": "application/json"
}
})
if (!response.ok){
console.log('response was not okay');
throw new Error('response was not okay');
}
console.log('response was okay');
const data = await response.json()
console.log(data);
return data;
} catch (error){
console.log(error);
}
}
Cors configuration (back end):
app.use(
cors({
origin:
process.env.NODE_ENV === 'development'
? process.env.DEV_ORIGIN
: process.env.PROD_ORIGIN,
credentials: true,
methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
}),
);
Session config (back end):
app.use(session({
store: new pgSession ({
// connect-pg-simple options:
pool : pgPool,
tableName : "session"
}),
secret: [THE SECRET],
saveUninitialized: true,
resave: false,
cookie: { maxAge: 30 * 24 * 60 * 60 * 1000 } // 30 days
}));
Be really grateful for any help, thanks!
Typical I'd figure out the answer also immediately after posting the question. It wasn't that I had to edit header settings for the get request once the user had already logged in, they had to already have been set at the point the user was logging in. Added the following to the headers for the login POST request and now it's all working:
"Access-Control-Allow-Credentials": true,
"Access-Control-Allow-Origin": true,
"Access-Control-Allow-Headers": true,
"Access-Control-Allow-Methods": true
More detailed:
const response = await fetch(`${API_ENDPOINT}/login`, {
method: "POST",
body: JSON.stringify({
username: email,
password: password
}),
credentials: 'include',
mode: 'cors',
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Credentials": true,
"Access-Control-Allow-Origin": true,
"Access-Control-Allow-Headers": true,
"Access-Control-Allow-Methods": true
}