1

I have started using express-session. But I am not receiving any cookie in response. Here is my code:

app.use(session({
    secret: 'jdfgghuheghgjbfhfguhrughhdjdjhjghj',
    saveUninitialized: false,
    resave: false
}))

app.post('/api/login', async (req, res) => {
    const {email, password} = req.body
    //console.log(req.body)
    console.log(email, password)
    const resp = await User.findOne({email,password})
    // console.log(resp)

    if(!resp) {
        // console.log("incorrect details")
        res.json({
            success: false,
            message: "Incorrect details"
        })
        // user login is incorrect 
    } else {
        res.json({
            success: true 
        })
        req.session.user = email
        req.session.save()
        console.log("logging you in")
        //make a session and set user to logged in.
    }
 
})

Trying to get the user here:

app.get('/api/data', (req, res) => {
    console.log(req.session)
    res.send('User is =>' + req.session.user)
})
 

I should get a set-cookie in response header in the network tab. Can anyone please tell me where am I missing out?

2 Answers2

0

You can find the Cookie in the Chrome DevTools under:

Application > Storage > Cookies > URL of the express Server

Reference: Where is the express-session cookie hidden?

Also your cookie will inaccessible via Javascript unless you set httpOnly to false. Though i would not recommend it as it is a security measure added for cookies

Amstel D'Almeida
  • 630
  • 6
  • 13
0

How do you call your endpoint? Depending on the http request, you may need to send it with credentials.

This is the case when you send it via Postman or your frontend runs on a different port.

fetch('https://example.com', {
  credentials: 'include'
});

Here is a way it works for me on the server side: Maybe that helps you as well.

const sessionStore = new MongoStore({ mongooseConnection: connection });
const sessionMiddleware = session({
  secret: secret,
  saveUninitialized: false,
  resave: true,
  rolling: true,
  cookie: {
    maxAge: 1000 * 60 * 60 /* 60min */,
    httpOnly: false,
  },
  store: sessionStore,
});

app.use(sessionMiddleware);
Andre
  • 458
  • 5
  • 10