title: TypeError: req.flash is not a function - tried moving middleware
body: <p>I am working on a project for school and have been struggling to figure out the cause of</p>
  
  <pre><code>TypeError: req.flash is not a function
  </code></pre>
  
  <p>within my routing.</p>
  
  <p>I did exhaustive research and found the following solutions that seemed to have worked for other people, but not me:</p>
  
  <ul>
  <li>Ensuring <code>passReqToCallback: true</code> is set for the local strategy and that the case of 'back' is lowercase. </li>
  <li>I have moved <code>app.use(flash())</code> through various locations within the middleware stack and ensured that it came before my routes declaration. </li>
  </ul>
  
  <p>Here is what I've got.
  server.js</p>
  
  <pre><code>    'use strict';
  
  // Set Up =============================================
  var express = require('express');
  var session = require('express-session');
  var cookieParser = require('cookie-parser');
  var bodyParser = require('body-parser');
  var morgan = require('morgan');
  var ejs = require('ejs');
  var app = express();
  
  var passport = require('passport');
  var flash = require('connect-flash');
  
  const PORT = 8081; //For simplicity, since you need root to make it on port 80
  const HOSTNAME = "127.0.0.1";
  
  // Config =============================================
  
  require('./app/auth')(passport); //Configure passport
  
  app.use(morgan('dev')); //Logs to the console
  app.use(cookieParser()); //Cookies for Auth
  app.use(bodyParser.urlencoded({
      extended: true
  })); //Get info from html forms
  app.use(bodyParser.json());
  
  app.set('view engine', 'html'); //Use the template module to render html
  app.engine('html', ejs.renderFile);
  app.set('views', __dirname  + "/public/views/pages"); //Instruct the engine of the location of the views
  
  
  app.use(session({
      secret: 'hashmeupsomethinggood',
      resave: true,
      saveUninitialized: true
  })); //Set default values
  app.use(passport.initialize());
  app.use(passport.session()); //Login sessions
  app.use(flash()); //For 'Flashing' messages back to client
  
  
  app.use(express.static(__dirname +'/public')); //Serves static files to client
  
  // Routing =============================================
  
  //Initialize routing with application and configured passport
  require('./app/routes.js')(app, passport);
  
  // Run ==================================================
  
  //Run the server
  var server = app.listen(PORT, HOSTNAME, function () {
      var host = server.address().address;
      var port = server.address().port;
      console.log("Example app listening at http://%s:%s", host, port)
  });
  </code></pre>
  
  <p>routes.js</p>
  
  <pre><code>module.exports = function (app, passport) {
  
      app.get('/', function (req, res) { //Callback for main pages
          res.render("index.html");
      });
  
      app.get('/movies', function (req, res) { //Callback for movies display
          res.render("movies.html");
      });
  
      //Handler for User Login
      app.post('/userlogin',
          passport.authenticate('local-login', {
              failureFlash:true
          },
          function (req, res) {
  
              if (req.user) {
                  console.log("User " + req.user + " logged in");
                  res.redirect("index.html"); //redirect but this time will render as logged in
              } else {
                  console.log("Login Attempt");
                  res.json({flashInfo: req.flash('login')}); //respond with info
              }
  
          }
          )
      );
  
  };
  </code></pre>
  
  <p>auth.js</p>
  
  <pre><code>var LocalStrategy = require('passport-local').Strategy; //For authenticating email and password
  var mysql = require('mysql');
  var connection = require('./connection');
  
  //Set up mysql
  var sqlCon = mysql.createConnection(connection);
  
  module.exports = function (passport) {
  
  // Session Setup ==============================================================
  // Needed for persistent logins
  
      //Serialize user id to identify session
      passport.serializeUser(function (user, done) {
          console.log("[Auth] Checking Login of " + user.EMAIL);
          if (user.ID) //User logging in is a customer OR employee - check both
              done(null, user.ID);
          else
              done(null, user.SSN);
      });
  
      //Obtain user object based on session user id
      passport.deserializeUser(function (id, done) {
  
          connection.query( //todo: add support for the employee here too
              "SELECT * FROM customers WHERE EMAIL = ?",
              [id],
              function (err, results, field) {
                  done(err, results[0]);
              }
          );
      });
  
  // Login ==============================================================
  
      passport.use(
          'local-login',
          new LocalStrategy({
              usernameField: 'email',
              passwordField: 'password',
              passReqToCallback : true
          },
          function (req, email, password, done) {
              console.log("[Auth] Checking Login of " + email);
              //Query for customer credentials
              connection.query("SELECT * FROM customers WHERE EMAIL = ?",
                  [email],
                  function (err, results) {
                      console.log("[Auth] First query");
                      if (err) {
                          console.log("[Auth] Error Accessing Database");
                          return done(err); //Error accessing database
                      } else {
                          if (results.length == 0) { //Could possibly be an employee logging in
  
                              //Query for employee credentials
                              connection.query("SELECT * FROM employee WHERE EMAIL = ?",
                                  [email],
                                  function (err, results) {
                                      if (err) {
                                          return done(err); //Query failed
                                      } else {
                                          if (results.length == 0) {//Does it exist in employee either?
                                              console.log("[Auth] Could not find user");
                                              return done(null, false, req.flash("login", "A user by that name does not exist!"));
                                          }
                                          return passwordCheck(results[0]); //Verify password
  
                                      }
  
                                  }
  
                              )
                          }
                          return passwordCheck(results[0]);
                      }
                  });
  
              //Determines the validity of a password and returns the corresponding verify callback function
              var passwordCheck = function (result) {
                  console.log("[Auth] Verifying Password of " + email);
                  if (result.PASSWORD == password)
                      return done(null, result);
                  else
                      return done(null, false, req.flash("login", "Incorrect Password"));
  
              };
          }
          )
      );
  
  // Register ==============================================================
  
      passport.use(
          'local-register',
          new LocalStrategy({
                  usernameField: 'email',
                  passwordField: 'password',
                  passReqToCallback : true
              },
              function (req, email, password, done) {
                  //Grab form data
                  var data = [req.body.fname, req.body.lname, req.body.bday, req.body.gender, email, password] //Form data
  
                  //Check that input isnt empty
                  if (data.includes("")) {
                      console.log("User %s registed with empty form", email);
                      return done(null, false, req.flash("register", "Please make sure not to leave anything blank"));
                  }
  
                  //Check that we arent making a duplicate account
                  connection.query(
                      "SELECT * FROM customer WHERE EMAIL = ?",
                      [email],
                      function (err, results) {
                          if (err) {
                              done(err);
                          }
  
                          //Check if the email has been taken
                          if (results.length &gt; 0) {
                              done(null, false, req.flash("register", "That email has already been taken"));
                          } else {
  
                              //User for session
                              var newUser = {
                                  EMAIL: data[4],
                                  PASSWORD: data[5],
                                  FNAME:data[0],
                                  LNAME: data[1],
                                  BDAY: data[2],
                                  SEX: data[3]
                              };
  
                              connection.query(
                                  "INSERT INTO customer(FNAME, LNAME, BDATE, SEX, EMAIL, `PASSWORD`) " +
                                  "VALUES (?, ?, STR_TO_DATE(?, '%m/%d/%y'), ?, ?, ?)",
                                  data,
                                  function (err, results) {
                                      newUser.ID = results.insertId; //Add ID
                                      return done(null, newUser);
                                  }
                              )
  
                          }
  
                      })
  
  
              }
          )
      );
  
  };
  </code></pre>