Learning node.js encountered this error "Login sessions require session support. Did you forget to use express-session
middlewar?" Has anyone encountered this specific error when creating a Node.js project and, if so, what did you do to solve?
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const passport = require('passport');
const path = require('path');
const config = require('./config/db');
const account = require('./routes/account');
const session = require('express-session');
const app = express();
const port = 3000;
app.use(passport.initialize());
app.use(passport.session());
require('./config/passport')(passport);
app.use(cors());
app.use(bodyParser.json());
mongoose.connect(config.db);
mongoose.connection.on('connected', () => {
console.log("Successful connection to the database")
});
mongoose.connection.on('error', (err) => {
console.log("Not successful connection to the database")
});
app.listen(port, () => {
console.log("The server was running on the port: " + port)
});
app.get('/', (req,res) => {
res.send("Home page")
});
app.use('/account', account);
const express = require('express');
const router = express.Router();
const User = require('../models/user');
const passport = require('passport');
const jwt = require('jsonwebtoken');
const config = require('../config/db');
router.post('/reg', (req,res) => {
let newUser = new User({
name: req.body.name,
email: req.body.email,
login:req.body.login,
password: req.body.password,
});
User.addUser(newUser, (err, user) => {
if(err) {
res.json({success: false, msg: "User has not been added."})
}
else {
res.json({success: true, msg: "User has been added"})
}
})
});
router.get('/auth', (req,res) => {
res.send("Login page")
});
router.get('/dashboard', passport.authenticate('jwt', {session : false}), (req,res) => {
res.send("Dashboard")
});
module.exports = router;
4
Answers
The error is asking a relevant question: "Did you forget to use express-session middleware?".
And indeed, you’re loading
passport.session()
but you’re not usingexpress-session
, which is a requirement.To fix it, use
express-session
before usingpassport.session()
:I faced same problem. But the real problem lied in the "passport" version compatibility with JWT module. By downgrading from passport 0.8.0 to 0.4.0 the issue was easily resolved. My code worked fine with the following configuration:
I don’t have a high enough reputation to add a comment to the answer telling you to downgrade your passport version, but doing so can introduce vulnerabilities…
Instead, look at https://www.npmjs.com/package/passport and see if your app has this: (version 0.6.0)
For me, the fix was telling express to use ‘express-session’.
I got this error when I’m using passport google Oauth and JWT token without session. In order to solve this error, I had to set the session to false in google callback. Here is my example: