Login sessions require session support. Did you forget to use `express-session` middleware

Issue

I am getting the error after req.logIn. I’ve tried everything but I don’t know why i am getting this error even I am using express-session and passport session. I also tried some tutorials but still i am getting this error

Login sessions require session support

router.post('/sign-in', function (req, res, next) {
  passport.authenticate('local-user', function (err, user, info) {
    if (err) {
      return next(err)
    }
    if (!user) {
      console.log('User not exist')
      return res.render('login')
    } else {
      req.logIn(user, function (err) {
        if (err) {
          return next(err)
        }
        req.session.isLoggedIn = true
       req.session.user = user
       req.session.save(err => {
         console.log(err)
         if (req.isAuthenticated()) {
           return res.redirect('/dashboard')
         }
         console.log('user not exist')
         return res.redirect('/sign-in')
       })
     })
   }})(req, res, next)
})

app.js

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const mongoose = require('mongoose')
const session = require('express-session')
const bodyParser = require('body-parser')
let MongoStore = require('connect-mongo');
const passport = require('passport')
var app = express();
require('./auth/passportAuthentication')(passport)

var signUpRoute = require('./routes/signUp');
var signInRoute = require('./routes/signIn');
const flash = require('connect-flash')  

app.use(cookieParser());
app.use(express.urlencoded({ extended: true }));
app.use(session({
  secret: '7861',
  resave: false,
  saveUninitialized: false,
  cookie: {
    secure: true,
    maxAge: 3000000 *60
  },
  store: MongoStore.create({
    mongoUrl:'mongodb+srv://name:password%[email protected]/?retryWrites=true&w=majority', 
   collection: 'session',
   ttl: 28800 
  })
}))

app.use(passport.initialize())
app.use(passport.session())
app.use(flash()) 

Solution

I am not sure but I think you have to use app.use(session { … }) before this line.

require('./auth/passportAuthentication')(passport)

I hope it will work,

app.use(session({
  secret: '7861',
  resave: false,
  saveUninitialized: false,
  cookie: {
    secure: true,
    maxAge: 3000000 *60
  },
  store: MongoStore.create({  
    mongoUrl:'mongodb+srv://name:password%[email protected]/?retryWrites=true&w=majority', 
    collection: 'session',
    ttl: 28800 
  })
}))

Answered By – usman imtiaz

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published