1

Having issues with node express-session and basically just trying to understand how it all works with regards to cookies and my session store within my postgres database.

For starters, I'm not sure why I don't receive a session id cookie within my chrome browser where my react app is running on localhost:3000. If I call the route localhost:5000/login from postman, a cookie is received but when calling the same route from Chrome: localhost:5000/login and then check my cookies, nothing is created when using the fetch API.

The session is created fine within postgres.

Here is my middleware for session setup:

app.use(session({
  store: new pgSession({
    pool : pool,                // Connection pool
    schemaName: 'my_schema',
    tableName : 'user_sessions'       
  }),  
  secret: randomString.generate({
    length: 14,
    charset: 'alphanumeric'
  }),
  resave: false,
  saveUninitialized: false,
  cookie: { maxAge: 1000 * 60 * 60 * 24,
            httpOnly: true }  
}))


app.use(function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
  next();
});

My other question is, within my react app, how can I use the session info within my postgres db to check that all requests to all routes are still coming from the same user on the client side?

ArthurJ
  • 777
  • 1
  • 14
  • 39

1 Answers1

0

try this , change your cors middleware this

 app.use(cors({ origin: true, credentials: true }));

and add this when you make your request

 withCredentials: true,
   credentials: "include",

I had same problem I was recieving the cooking when making post from postman, but not from the browser when making request with axios, hopefully it works for you too as well

  • FYI, I'm not using Axios, I'm actually using the fetch API - does this make a difference? – ArthurJ Jul 25 '21 at 08:58
  • @ArthurJ, no it doesnt, just figure out how to credentials and withCredentials to your request options, I don't really use fetch API xd – Lhon Rafaat Mohammed Jul 25 '21 at 09:04
  • Will do but from what I can see, when I add `credentials: "include"` to my fetch login route, this now no longer works. I even added `res.header('Access-Control-Allow-Credentials', 'true')` and it made no difference. – ArthurJ Jul 25 '21 at 09:22
  • hmm I still suspect your request options setup, make sure you have used the right options, -- credentials Controls what browsers do with credentials (cookies, HTTP authentication entries, and TLS client certificates). I can't think of any other thing that blocks setting cookies to the browser other than the credentials. – Lhon Rafaat Mohammed Jul 25 '21 at 09:51