8

I'm having some problems getting connect-flash to work, the error message I'm getting is:

'Error: req.flash() requires sessions'

I've seen this can be because of the ordering of the app, but I'm not sure if this is the case here.

App.js:

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var flash = require('connect-flash');
var passport = require('passport');
var app = express();

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(session({secret: '{secret}', name: 'session_id', saveUninitialized: true, resave: true}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());

Routes etc. are below

flash generating code:

passport.authenticate('local', { failureRedirect: '/login', successRedirect: '/', failureFlash: true})
Ash
  • 6,483
  • 7
  • 29
  • 37
  • so, just removing your prefix yields following question here on SO: http://stackoverflow.com/questions/19168355/req-flash-requires-sessions –  May 31 '15 at 19:00
  • I've already read that, I don't use session.destroy() anywhere. Any other ideas? – Ash May 31 '15 at 19:03
  • [Passport needs flash to be configured *before* itself](http://stackoverflow.com/questions/19984996/setting-up-connect-flash-middleware-for-use-by-passport). Try putting `app.use(flash())` before passport – laggingreflex May 31 '15 at 21:29
  • 1
    In my case the RedisStore object in the store property of the express-session was wrongly configured (wrong port). – flaudre Mar 15 '16 at 16:05
  • 1
    Same here -- didn't have Redis running the background. – Nathan Bertram Apr 20 '16 at 05:02

2 Answers2

5

The issue was with how my view was getting rendered (using req.flash data)

Changing this:

loginShow: function(req, res){
    res.render('login', { message: req.flash });
}

To this:

loginShow: function(req, res){
    res.render('login', { message: req.flash() });
}

Fixed the error and causes connect-flash to act as expected.

Ash
  • 6,483
  • 7
  • 29
  • 37
5

Is your redis-server running? Try

redis-server

This solved the issue for me.

flaudre
  • 2,358
  • 1
  • 27
  • 45