DEV Community

Shreelaxmi Hegde
Shreelaxmi Hegde

Posted on

Auth Series #3: Authentication implementation using Passport.js

Previous : Auth Series #2: Authentication Implementation with Passport.js

There are two ways to implement authentication system:

  1. Build a custom authentication system from scratch, or
  2. Use existing, battle-tested tools that simplify the process.

Among the many options available, Passport.js stands out as one of the most popular and widely used libraries for Node.js applications. It blends easily with MongoDB (via Mongoose) and offers a modular structure that supports both local and third-party authentication (like Google, GitHub, or Facebook).


📌 Why Passport.js?

Passport.js provides a clean, flexible API and powerful features that make authentication smooth and reliable:

▹ Built-in middlewares and methods speed up development.
▹ Uses strong salting and hashing techniques to protect passwords.
▹ Works seamlessly with MongoDB + Mongoose.
▹ Supports multiple authentication strategies (local, OAuth, etc.).


3.1 Setting Up Passport.js :
First, install the necessary packages from npm:

npm install passport
npm install passport-local         # Local strategy
npm install passport-local-mongoose # Mongoose plugin
Enter fullscreen mode Exit fullscreen mode

The local strategy is used for authentication systems that rely on standard login fields like username, email, and password instead of third-party logins.

3.2 Initialize Passport in your Express app:

app.use(passport.initialize()); // Sets up Passport middleware
Enter fullscreen mode Exit fullscreen mode

3.3 Defining the User Schema :

We’ll use Mongoose to define our user schema. The passport-local-mongoose plugin automatically adds username and password fields, and handles the salting and hashing of passwords behind the scenes so we don’t need to code that manually.

const passportLocalMongoose = require("passport-local-mongoose");
const userSchema = new Schema({ 
   email: String
}); // user schema definitions
userSchema.plugin(passportLocalMongoose); // Connects schema with Passport’s helper methods
Enter fullscreen mode Exit fullscreen mode

3.4 Registering a New User Using Passport.js through the /signup Route

We’ve already discussed that when a user submits the signup form, the browser sends a POST request to the /signup route, where the server stores their credentials in the database.

Here’s what the route looks like :

app.post("/signup", async(req, res) => {
   let { username, email, password} = req.body;
   const newUser = new User({email, username});
   const registeredUser = await User.register(newUser, password);
});
Enter fullscreen mode Exit fullscreen mode

What does this code do?
⤷ It takes all the credentials submitted by the user through the signup form.
⤷ It creates a new user using the Mongoose User schema, which stores the email and username.
⤷ The User.register() method then handles password hashing, salting, and saving the final user document to the database

More clarification on User.register() method

  • The .register() method is provided by the passport-local-mongoose plugin, which we attached while defining our User schema.
  • It automates most of the registration process by handling the following steps internally :
    • Generates salt
    • Hashes the password using that salt.
    • stores both salt and hashed password in the User document.
    • Saves the user in the database.

In this way we have successfully built an Authentication system.🥳

It's time to move to another interesting and most important part : Cookies and Sessions in Express.js.

Top comments (0)