nodeJS/Express TypeError "passport-authenticate is not a function"

Hello I have been stuck on various issues while following a guide on how to setup a shopping cart in nodeJS/Express/MongoDb. The guide is a few years old , and I have been trying to find help in the comments with no luck. My issue is that when trying to start the server , I get an error saying : TypeError : passport.authenticate is not a function.

it is refering to my index.js file which looks like this :

var express = require('express');

var router = express.Router();

var Product = require('D:/Other/Projects/Code/Powershell/shopping-cart/models/product');

var csrf = require('csurf');

var passport = require('D:/Other/Projects/Code/Powershell/shopping-cart/config/passport.js');

var csrfProtection = csrf();

router.use(csrfProtection);

/* GET home page. */

router.get('/', function(req, res, next) {

  Product.find(function(err, docs) {

    var productChunks = [];

    var chunkSize = 3;

    for (var i = 0; i < docs.length; i += chunkSize) {

           productChunks.push(docs.slice(i, i + chunkSize));

    }

    res.render('shop/index', { title: 'Shopping Cart', products: productChunks });

  });

});

router.get('/user/signup', function (req, res, next) {

   res.render('user/signup', {csrfToken: req.csrfToken()});

});

router.post('/user/signup', passport.authenticate('local.signup'), {

  successRedirect: '/user/profile',

  failureRedirect: '/user/signup',

  failureFlash: true

});

router.get('/user/profile', function(req, res, next) {

  res.render('user/profile');

});

module.exports = router;

And this is how my app.js file is looking :

var createError = require('http-errors');

var express = require('express');

var path = require('path');

var cookieParser = require('cookie-parser');

var logger = require('morgan');

var routes = require('./routes/index')(passport);

var indexRouter = require('./routes/index');

var usersRouter = require('./routes/users');

var expressHbs = require('express-handlebars');

var mongoose =require('mongoose');

var app = express();

var session = require('express-session');

var passport = require('passport');

var flash = require('connect-flash');

const bodyParser = require('body-parser');

mongoose.connect('mongodb://localhost:27017/shopping', {useNewUrlParser: true, useUnifiedTopology: true});

mongoose.connection.on('error', err => {

  throw 'failed to connect to MongoDB';

});

require('passport');

// view engine setup

app.engine('.hbs', expressHbs({defaultLayout: 'layout', extname:'.hbs'}))

app.set('view engine', '.hbs');

app.use(bodyParser.urlencoded({extended: false}));

app.use(bodyParser.json());

app.use(logger('dev'));

app.use(express.json());

app.use(express.urlencoded({ extended: false }));

app.use(cookieParser());

app.use(session({secret: 'mysupersecret', resave: false, saveUninitialized: false}))

app.use(flash());

app.use(passport.initialize());

app.use(passport.session());

app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);

app.use('/users', usersRouter);

// catch 404 and forward to error handler

app.use(function(req, res, next) {

  next(createError(404));

});

// error handler

app.use(function(err, req, res, next) {

  // set locals, only providing error in development

  res.locals.message = err.message;

  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page

  res.status(err.status || 500);

  res.render('error');

});

module.exports = app;

And here is my passport.js file :

`var passport = require ('passport');`
`var User = require('D:/Other/Projects/Code/Powershell/shopping-cart/models/user');`
`var LocalStrategy = require ('passport-local').Strategy;`
`var mongoose = require('mongoose');`
`passport.serializeUser(function(user, done) {`
`done(null, user.id);`
`});`
`passport.deserializeUser(function(id, done) {`
`User.findById(id, function(err, user){`
`done(err, user);`
`});`
`});`
`passport.use('local.signup', new LocalStrategy({`
`usernameField: 'email',`
`passwordField: 'password',`
`passReqToCallback: true`
`}, function(req, email, password, done){`
`User.findOne({'email': email}), function(err, user){`
`if (err) {`
`return done(err);`
`}`
`if (user) {`
`return done (null, false, {message: 'Email is already in use'});`
`}`
`var newUser = new User ();`
`newUser.email = email;`
`newUser.password = newUser.encryptPassword(password);`
`newUser.save(function(err, result) {`
`if (err) {`
`return done(err);`
`}`
`return done(null, newUser);`
`});`
`};`
`}));`

Any hints on what could be the issue? all help is appreciated, thanks!

Hi,

I’m afraid it is a bad idea to follow tutorials that are outdated by years. The JavaScript landscape moves pretty quickly and you’ll just end up tying yourself in knots with errors, deprecation warnings and so on.

Therefore, my advice would be to find a tutorial that is more up-to-date and follow that. You will save yourself a lot of trouble in the long run. A quick search turned up this, which (according to the search results, at least) is from Feb 2020 and seems to be what you are after.

That said, I’m not that sure what is causing your problem — I’d really need to have enough code to reproduce your error. A quick search however, turns up:

That any help?

P.S. I’m assuming that is just bad formatting in passport.js (with all the backticks).

1 Like

Also, there’s this. Currently on offer for €10,99.

https://www.udemy.com/course/nodejs-express-project-cms-and-shopping-cart/

1 Like

Thanks for your advice, I have already tried the stackoverflow method you linked, and searched everywhere for an answer. It’s not the shopping-cart itself that is the problem, as I have another project that is nearly done with adding shop articles and payment and such. The reason I chose this old guide is because everything is way more organized and it includes everything from the shopping cart to creating an account and keeping track of the orders on your account and much more.

Edit : yes I tried to format the code so that it is easy to read, I guess I added too many backticks

I’m not overly familiar with Passport, so I’m not sure I’ll be able to help much, I’m afraid :frowning:

To maximize your chances of getting an answer, it’s normally a good idea to create a minimal example that people can run to reproduce the error you are having. If it involves several files, you can create a small repo and stick it up on GitHub.

Good luck!

1 Like

Thanks for your advice, I will keep trying to find an answer.

Can you give the full error, including any line numbers?

There’s another Stackoverflow question that might help, if you haven’t already seen it.

Hello , thanks for the link but I have already read that answer and did everything that was suggested, without further success. This is the full error :


D:\Other\Projects\Code\Powershell\shopping-cart\routes\index.js:25
router.post('/user/signup', passport.authenticate('local.signup'), {
                                     ^

TypeError: passport.authenticate is not a function
    at Object.<anonymous> (D:\Other\Projects\Code\Powershell\shopping-cart\routes\index.js:25:38)
    at Module._compile (internal/modules/cjs/loader.js:1158:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
    at Module.load (internal/modules/cjs/loader.js:1002:32)
    at Function.Module._load (internal/modules/cjs/loader.js:901:14)
    at Module.require (internal/modules/cjs/loader.js:1044:19)
    at require (internal/modules/cjs/helpers.js:77:18)
    at Object.<anonymous> (D:\Other\Projects\Code\Powershell\shopping-cart\app.js:7:14)
    at Module._compile (internal/modules/cjs/loader.js:1158:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
    at Module.load (internal/modules/cjs/loader.js:1002:32)
    at Function.Module._load (internal/modules/cjs/loader.js:901:14)
    at Module.require (internal/modules/cjs/loader.js:1044:19)
    at require (internal/modules/cjs/helpers.js:77:18)
    at Object.<anonymous> (D:\Other\Projects\Code\Powershell\shopping-cart\bin\www:7:11)
    at Module._compile (internal/modules/cjs/loader.js:1158:30)

npm ERR! Windows_NT 10.0.18363
npm ERR! argv "D:\\NodeJS\\node.exe" "C:\\Users\\musta\\AppData\\Roaming\\npm\\node_modules\\npm\\bin\\npm-cli.js" "start"
npm ERR! node v12.16.1
npm ERR! npm  v3.10.10
npm ERR! code ELIFECYCLE
npm ERR! shopping-cart@0.0.0 start: `node ./bin/www`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the shopping-cart@0.0.0 start script 'node ./bin/www'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the shopping-cart package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node ./bin/www
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs shopping-cart
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls shopping-cart
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     D:\Other\Projects\Code\Powershell\shopping-cart\npm-debug.log


Can you print out passport just above where it’s failing? Like this:

console.log(passport);
router.post('/user/signup'...

It may print a lot of stuff out. Just trying to debug remotely :slight_smile:

1 Like

Not sure what you mean. Should I add console.log(passport); above
router.post('/user/signup', passport.authenticate('local.signup'), { successRedirect: '/user/profile', failureRedirect: '/user/signup', failureFlash: true });

and then start the server and send you the error?

Right, give it a try and see what is printed out for passport. If it’s hugely long, you may not be able to post it all. Let’s just take a look at it.

1 Like

Sadly , I get the same error :

{}
D:\Other\Projects\Code\Powershell\shopping-cart\routes\index.js:26
router.post('/user/signup', passport.authenticate('local.signup'), {
                                     ^

TypeError: passport.authenticate is not a function
    at Object.<anonymous> (D:\Other\Projects\Code\Powershell\shopping-cart\routes\index.js:26:38)
    at Module._compile (internal/modules/cjs/loader.js:1158:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
    at Module.load (internal/modules/cjs/loader.js:1002:32)
    at Function.Module._load (internal/modules/cjs/loader.js:901:14)
    at Module.require (internal/modules/cjs/loader.js:1044:19)
    at require (internal/modules/cjs/helpers.js:77:18)
    at Object.<anonymous> (D:\Other\Projects\Code\Powershell\shopping-cart\app.js:7:14)
    at Module._compile (internal/modules/cjs/loader.js:1158:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
    at Module.load (internal/modules/cjs/loader.js:1002:32)
    at Function.Module._load (internal/modules/cjs/loader.js:901:14)
    at Module.require (internal/modules/cjs/loader.js:1044:19)
    at require (internal/modules/cjs/helpers.js:77:18)
    at Object.<anonymous> (D:\Other\Projects\Code\Powershell\shopping-cart\bin\www:7:11)
    at Module._compile (internal/modules/cjs/loader.js:1158:30)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! shopping-cart@0.0.0 start: `node ./bin/www`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the shopping-cart@0.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\musta\AppData\Roaming\npm-cache\_logs\2020-04-06T17_06_48_472Z-debug.log

Do you want me to post the debug.log?

That actually helps a little bit. As you can see, passport is being printed out. It is an empty object (see the two curly brackets at the top?) {}.

Can you show us what is in this file? D:/Other/Projects/Code/Powershell/shopping-cart/config/passport.js

Is it too long to post?

1 Like

Oh I see, here is my passport.js file :

var passport = require ('passport');

var User = require('D:/Other/Projects/Code/Powershell/shopping-cart/models/user');

var LocalStrategy = require ('passport-local').Strategy;

var mongoose = require('mongoose');

passport.serializeUser(function(user, done) {

    done(null, user.id);

});

passport.deserializeUser(function(id, done) {

      User.findById(id, function(err, user){

          done(err, user);

      });

    });

    passport.use('local.signup', new LocalStrategy({

        usernameField: 'email', 

        passwordField: 'password',

        passReqToCallback: true

    }, function(req, email, password, done){

         User.findOne({'email': email}), function(err, user){

             if (err) {

                 return done(err);

             }

             if (user) {

                 return done (null, false, {message: 'Email is already in use'});

             }

             var newUser = new User ();

             newUser.email = email;

             newUser.password = newUser.encryptPassword(password);

             newUser.save(function(err, result) {

                 if (err) {

                     return done(err);

                 }

                 return done(null, newUser);

             });

         };

    }));

I’m guessing, but possibly the issue is that nothing is exported from your passport.js file. Did you copy this code directly from the example you are following? Is it possible that you missed a line where the module was exported?

Sitepoint actually has a little article on exports.

1 Like

I re-watched the video guide and from what I can see, no module.export line is ever written.

this is the video, if you watch around 10 mins you can see the end of the file , and I watched through the video and I couldn’t see him writing any module.exports at the end of the file.

Edit: Should I rewatch the whole guide and re-write all the files that are written in this video?

I don’t see rewatching that video as being helpful. He doesn’t show all the source code.

Try this: in your index.js file, comment out this line:

var passport = require('D:/Other/Projects/Code/Powershell/shopping-cart/config/passport.js');

Replace it with:

var passport = require('passport');

and see what happens (restart server and test as before).

This time I got a new error :


Authenticator {
  _key: 'passport',
  _strategies: {
    session: SessionStrategy {
      name: 'session',
      _deserializeUser: [Function: bound ]
    }
  },
  _serializers: [],
  _deserializers: [],
  _infoTransformers: [],
  _framework: {
    initialize: [Function: initialize],
    authenticate: [Function: authenticate]
  },
  _userProperty: 'user',
  _sm: SessionManager {
    _key: 'passport',
    _serializeUser: [Function: bound ]
  },
  Authenticator: [Function: Authenticator],
  Passport: [Function: Authenticator],
  Strategy: [Function: Strategy] { Strategy: [Circular] },
  strategies: { SessionStrategy: [Function: SessionStrategy] }
}
D:\Other\Projects\Code\Powershell\shopping-cart\node_modules\express\lib\router\route.js:202
        throw new Error(msg);
        ^

Error: Route.post() requires a callback function but got a [object Object]
    at Route.<computed> [as post] (D:\Other\Projects\Code\Powershell\shopping-cart\node_modules\express\lib\router\route.js:202:15)
    at Function.proto.<computed> [as post] (D:\Other\Projects\Code\Powershell\shopping-cart\node_modules\express\lib\router\index.js:510:19)
    at Object.<anonymous> (D:\Other\Projects\Code\Powershell\shopping-cart\routes\index.js:27:8)
    at Module._compile (internal/modules/cjs/loader.js:1158:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
    at Module.load (internal/modules/cjs/loader.js:1002:32)
    at Function.Module._load (internal/modules/cjs/loader.js:901:14)
    at Module.require (internal/modules/cjs/loader.js:1044:19)
    at require (internal/modules/cjs/helpers.js:77:18)
    at Object.<anonymous> (D:\Other\Projects\Code\Powershell\shopping-cart\app.js:7:14)
    at Module._compile (internal/modules/cjs/loader.js:1158:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
    at Module.load (internal/modules/cjs/loader.js:1002:32)
    at Function.Module._load (internal/modules/cjs/loader.js:901:14)
    at Module.require (internal/modules/cjs/loader.js:1044:19)
    at require (internal/modules/cjs/helpers.js:77:18)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! shopping-cart@0.0.0 start: `node ./bin/www`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the shopping-cart@0.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\musta\AppData\Roaming\npm-cache\_logs\2020-04-06T18_21_20_899Z-debug.log

Hm, sorry but I can’t tell from this error message whether that was progress or not…

Where did you get your source code from? I see a link to a github project in the YouTube video’s description, but it looks way more simple than what you have, and also doesn’t use passport. So I’m just wondering how you built this project…

I do see some similar projects in github. It may be worth taking a look at github to find other people’s source code. Here’s one example.

I understand what you mean. I saw a few comments saying the “full” github project is available, but I only see the layout and some of the files. The files I got are from the actual videos, where I have been following him when he is writing the code. The reason I chose his guide is because I wanted a cart link in the actual navbar. I have another working project but the cart is in the body of the page. It is working however. I will check out the github link you sent me, thanks for the help.