In Passport Authentication for Node.js Applications, I talked about authentication using Passport as it relates to social login (Google, Facebook, GitHub, etc.). In this article, we’ll see how we can use Passport for local authentication with a MongoDB backend.


  • Node.js – Download and install Node.js.
  • Install Express using the command npm install -g express.
  • MongoDB – Download and install MongoDB. Note, if you’re using Ubuntu, this guide can help you get Mongo up and running.

Creating the Project

Once all of the prerequisite software is setup, we can create our Express server:

express LocalAuthApp
cd LocalAuthApp
npm install

Next, install the passport and passport-local Node modules using the following commands.

npm install passport
npm install passport-local

Next, start the node server using the following command. To verify that everything is setup correctly, point your browser to http://localhost:3000, where you should be greeted with an Express page.

node app.js

Implementing Local Authentication

In the views directory, create login.html, containing the following code.

    <form action="/login" method="post">
        <input type="text" name="username" />
        <input type="password" name="password" />
        <input type="submit" value="Submit" />

Inside app.js, add the following route:

app.get('/login', function(req, res) {

You can view the new login page by restarting the server and visiting /login. Next, let’s implement the login post method to handle authentication. In app.js, add these require() statements:

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

We also need to add the Passport middleware for authentication to work. Before the line that reads:


Add these two lines:


We also need to define the login handler routes, which are shown below.'/login',
  passport.authenticate('local', {
    successRedirect: '/loginSuccess',
    failureRedirect: '/loginFailure'

app.get('/loginFailure', function(req, res, next) {
  res.send('Failed to authenticate');

app.get('/loginSuccess', function(req, res, next) {
  res.send('Successfully authenticated');

Passport also needs to serialize and deserialize the user instance, so add the following code.

passport.serializeUser(function(user, done) {
  done(null, user);

passport.deserializeUser(function(user, done) {
  done(null, user);

Next, define the local authentication strategy, as shown below. Note that we will add the authentication check logic later.

passport.use(new LocalStrategy(function(username, password, done) {
  process.nextTick(function() {
    // Auth Check Logic

Creating a MongoDB Data Store

Start the mongod server using the following command:

mongod --config /etc/mongodb.conf

From another terminal launch the Mongo shell:


Within the shell, issue the following commands:

use MyDatabase;


The first command creates a data store named MyDatabase. The second command creates a collection named userInfo and inserts a record. Let’s insert a few more records:


Retrieving Stored Data

We can view the data we just added using the following command:


The resulting output is shown below:

{ "_id" : ObjectId("5321cd6dbb5b0e6e72d75c80"), "username" : "admin", "password" : "admin" }
{ "_id" : ObjectId("5321d3f8bb5b0e6e72d75c81"), "username" : "jay", "password" : "jay" }
{ "_id" : ObjectId("5321d406bb5b0e6e72d75c82"), "username" : "roy", "password" : "password" }

We can also search for a particular username and password:


This command would return only the admin user.

Connecting to Mongo from Node

We’ll be using Mongoose to connect to MongoDB from our Node application. From the terminal, type npm install mongoose to install the Mongoose module. Next, add Mongoose to app.js using the following code.

var mongoose = require('mongoose/');


We’ll use schemas and models to work with data in Mongo. Schemas define the structure of the data inside a collection, and models are used to create instances of data. So, let’s create one:

var Schema = mongoose.Schema;
var UserDetail = new Schema({
      username: String,
      password: String
    }, {
      collection: 'userInfo'
var UserDetails = mongoose.model('userInfo', UserDetail);

It’s time to include our logic to authenticate the user using the UserDetails model. Here is how we do it:

passport.use(new LocalStrategy(function(username, password, done) {
  process.nextTick(function() {
      'username': username, 
    }, function(err, user) {
      if (err) {
        return done(err);

      if (!user) {
        return done(null, false);

      if (user.password != password) {
        return done(null, false);

      return done(null, user);

We simply used the same command that we used in the mongo shell to find a record based on the username. If a record is found and the password matches then the above code returns the user object. Otherwise, it returns false.

Restart your node server and point your browser to http://localhost:3000/login and try to login.


In this article, we learned about how to implement local authentication using Passport in a Node.js application. In the process, we also learned how to connect to MongoDB using the Mongoose. All of the code from this article is available for download on GitHub.

Tags: passport
Jay is a Software Engineer and Writer. He blogs occasionally at Code Handbook and Tech Illumination.

Free Guide:

How to Choose the Right Charting Library for Your Application

How do you make sure that the charting library you choose has everything you need? Sign up to receive this detailed guide from FusionCharts, which explores all the factors you need to consider before making the decision.

  • Eduardo Royer

    Great article Jay Raj. I tested it and it works great.

  • Alex Ivanovs
  • Francis Bissonnette

    TypeError: Cannot call method ‘initialize’ of undefined

    And I didn’t skip any step. Help! Thx!

    • Jay

      make sure u have passport installed…..and app declared….

  • Luke Bonaccorsi

    No no no no no no no!

    Unencrypted passwords? Seriously?

  • Allan Ebdrup

    unhashed passwords and mongoose…
    Might I suggest salting and hashing passwords with for example bcrypt, and using mongojs instead of mongoose?

    • Jay

      off course ….but the tutorial just focused on doing local authentication ….salting and hashing is off course necessary

  • Jay

    thnks Alex :)

  • Jay

    thnks Eduardo :)

  • Guest

    Thank you, Jay. If, on success, instead of “res.send(‘Successfully authenticated’);” I wanted to return the user object of that particular user from the JSON file, how would I go about that?

  • Blake

    Thank you Jay!

    Is it possible to use passport to authenticate from a single field, instead of user/password combo? Like, a user is provided a unique code, he enters the code, and passport checks the DB for a match?

  • mabel

    What is the purpose of process.nextTick?

  • Tom Dworzanski

    Thanks for the tutorial.

    This tutorial however is very insecure because you’re storing passwords as plain-text in the database. Please consider using a key derivation function such as PBFDK2, bcrypt, or scrypt on the passwords in Mongo. People are using this solution in real applications and it’s dangerous to the Internet to post this sort of lacking solution. Thank you for your consideration.

  • Larry Eliemenye

    for some odd reasons my “verifier” function never gets called. Hitting the /login route(method is post, form values are username and password just like the default fields) always ends up calling the failureRedirect handler. Any idea why this is happeneing?

  • chan cs

    Hi jay am new to nodejs and i need to a userlogin for my website and i followed user tutorial when i clicks the submit in login page i suppose to wait for a long time and at the end of 5-10 minutes am geetting “NO DATA FOUND” in the page when i look in to my terminal am getting the following lines of messages Express server listening on port 3000

    GET /login 304 15ms

    POST /login 200 120001ms

    POST /login 200 120006ms

    can you fix my problem

  • ppsh

    For people ask for hash salt etc.. you can just see about “passport-local-mongoose” do. and use it. Else if you understand this tutorial, you can easily do this using Express 4 .. differents routes management but I’m noob on nodejs and now I’m looking for session uses.

    Thanks Jay that introduce me to Express, Mongo, Passport stack.

    I think you just need to do an update with Express 4, Use Jade than simple html, use passport-local-mongoose, use session, and finish by tests :)

    • guest

      that’s a good suggestion of updating this tutorial :)

  • Yogesh

    Thank You!

  • Mayank Tripathi

    Authentication and logins in Node may be a sophisticated factor. Truly work sure any application may be a pain. This text series can influence authenticating in your Node application victimization the package Passport.

    Passport is authentication middleware for Node. It’s designed to serve a singular purpose: evidence requests. Once writing modules, encapsulation could be a virtue, therefore Passport delegates all alternative practicality to the appliance. This separation of issues keeps code clean and reparable, associate degreed makes Passport very simple to integrate into an application.

    In modern web applications, authentication can take a variety of forms. Traditionally, users log in by providing a username and password. With the rise of social networking, single sign-on using an OAuth provider such as Facebook or Twitter has become a popular authentication method. Services that expose an API often require token-based credentials to protect access.

    for full implementation refer here:

  • Mayank Tripathi

    These simple steps are follow to implement the this:

    Step 1: Folder Structure of the Application
    Step 2: Install Dependency
    Step 3: Add app.js for Application Setup
    Step 4: Configure Database
    Step 5: Create Views
    Step 6: Create User Model
    Step 7: Create Route
    Step 8: Handle Authentication

    For full implementation refer here:

  • gunni

    same issue hitting login gives me failureRedirect . It never invokes the method passport.use. Can any one help me in thiS??

  • Supraja

    Hi Jay.. i get this error “TypeError: Cannot call method ‘findOne’ of undefined” Can you help me out pls

  • Sriman Abimanyu

    Whenever the password is given. only AUTHENTICATION failure is returned. How to resolve?

  • kilencvennyolc

    Sorry but this example is not working for me. I downloaded it and also installed all vendors by npm but no result. It does not show the login page. I can see strange 404 errors in the console when I try to open the login page.

  • Claud Hu

    Thanks your sharing, A great tutorial

    but I wanna know whether there are the same steps between express 4.0 and 3.0?

  • r p

    Is it the same steps with postgres database instead of mongodb?

Special Offer
Free course!

Git into it! Bonus course Introduction to Git is yours when you take up a free 14 day SitePoint Premium trial.