Search code examples
javascriptnode.jsexpressmulterexpress-session

Data in express session disappear when upload file


I'm developing a web server and trying to make upload file route. But I need only people who logged in can upload a file. So I add middleware that checks if the session data's available. But session data alway is undefined in this route.

I tried to reload and to regenerate session but it still is undefined. And I changed the library from "multer" to "express-fileupload" but it does not effect. Maybe because the type of content is multipart-form-data. I'm not sure.

Session middleware set up.

const sessionMidleware = session({
  secret: 'My secret key',
  resave: false,
  saveUninitialized: false,
})

app.use(sessionMidleware)

The middleware that I inserted for debugging.

app.post(
  '/sendinvoice',
  (req, res, next) => {
    console.log(req.session)
    next()
  },
  uploadCustomerInvoice().fields([
    { name: 'file', maxCount: 1 },
    { name: 'course_id', maxCount: 1 },
  ]),
  customerInvoice,
)

this is a function that I use for setting up a session in other routes when login and register.

module.exports = (req, profile, courses) => {
  req.session.profile = profile
  req.session.courses = courses
  req.session.isSuper = false
  req.session.isAdmin = false
  req.session.save()
}

I expect the output of req.session.profile to object that store user data, but the actual output is undefined.


Solution

  • I finally figured out that session disappeared because I forgot to send the cookie with the request. I'm using Fetch API. So I add credentials: 'include' to the header then it work. Thank you.