Passport-Local Authentication

I would like to share how I configured Passport.js for my Node.js Express Server. I was looking for something to refer but couldn’t find any matching my requirements. I was working on a web-app that needed authentication that was not so complex but yet efficient.

Photo by Jason Strull on Unsplash

My requirements were:

  1. Authenticate using email and password
  2. Separate routes for login and signup

Based on the requirements, I encountered Passport.js, which is an authentication middleware for Node.js. It’s simple way of implementation made me explore it.

Photo by Samuel Regan-Asante on Unsplash

Here’s the folder structure of my server:

Here’s how I configured my Node Express Server to authenticate using Passport.js:

index.js

The user schema can be defined as:

models/User.js

Now, let’s configure the local strategy for Passport.js authentication.

Passport.js can be used for various authentication mechanisms, these are known as strategies.

Here, I needed email-password authentication, so, I used passport-local strategy which authenticates using username and password.

We can modify the strategy to use email as usernameField, so that there are no confusions for authenticating.

config/passport-config.js

Now, let’s define the routes in the auth.js file:

By now, we have implemented passport.js for authenticating our users.

We can now test the API by running the index.js file using the command:

Which will give the output:

Output

I used Postman for testing my API. Try sending requests to localhost:9000/users/register & localhost:9000/users/login and check whether the required response is obtained.

Congrats! Now you have completed the authentication part for your server. Thank you for taking time reading this article. Hope this was beneficial for you.

MEVN Stack Web Developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store