Home » Node.js

Passport local strategy section 2 | Node.js

Node.js | Passport local strategy: Here, we are going to learn about the further steps to setup passport module (various requirements for setting up the passport-local strategy with Node.js/Express and MongoDB database).
Submitted by Godwill Tetah, on September 16, 2019

In my last article (Passport local strategy section 1 | Node.js), we started the implementation of the passport-local authentication strategy. We also looked at the various requirements to get started with the login form. In this article, we will continue with setting up passport and MongoDB database.

These codes are just to help you get started. So you can edit them.!

Passport setup

In the app.js file, add the following code at the bottom


const passport = require('passport');

app.get('/success', (req, res) => res.send("Welcome "+req.query.username+"!!"));
app.get('/error', (req, res) => res.send("error logging in"));

passport.serializeUser(function(user, cb) {
  cb(null, user.id);

passport.deserializeUser(function(id, cb) {
  User.findById(id, function(err, user) {
    cb(err, user);

The code above requires the passport module and creates 2 additional routes which handles successful login and when there's an error.

Mongoose setup

Before setting up mongoose, first of all, create a database with name MyDatabase with collection userInfo and add some few records as shown below:

passport module 6

Mongoose is what helps our node application to connect with our MongoDB database. It makes use of schema and models.

Schema helps us define our data structure and is later used to create our model as you'll see later in the code.

First of all install mongoose by running the following command in a terminal:

passport module 7

In the app.js file, add the following code at the bottom


// schema

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/MyDatabase', { useNewUrlParser: true } );

const Schema = mongoose.Schema;
const UserDetail = new Schema({
      username: String,
      password: String

// model

const UserDetails = mongoose.model('userInfo', UserDetail, 'userInfo');

That's all for this second section. In the last section, we are going to set up our passport-local authentication strategy since we are working on a form and finally test our work.

Thanks for coding with me! See you @ the next article. Feel free to drop a comment or question.

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.