How to Create Login and Register in Node.js

Websolutionstuff | Oct-02-2023 | Categories : Node.js

As I embarked on my journey to develop a powerful web application, I realized the importance of a robust user authentication system. In this tutorial, I'll take you through the creation of a full-fledged login and registration system using Node.js, Express, and MongoDB.

Together, we'll build a secure and efficient system that allows users to register, log in, and access personalized profiles.

By the end of this guide, you'll not only have a functioning authentication system but also a deeper understanding of how to implement similar features in your own Node.js projects.

So, let's dive in and explore the world of user authentication, one step at a time, and login and registration form in node.js.

login_and_register_in_node_js

Below is a step-by-step guide to help you build a basic login and registration system using Node.js, Express, and MongoDB as a database.

Step 1: Set Up Your Project

First, create a new directory for your project and initialize it with npm.

mkdir node-authentication
cd node-authentication
npm init -y

Install the necessary packages.

npm install express express-session passport passport-local mongoose bcrypt connect-flash

 

Step 2: Create Your Directory Structure

Create the following directory structure.

- node-authentication/
  - node_modules/
  - public/
    - css/
    - js/
  - views/
  - app.js
  - package.json

 

Step 3: Set Up Your MongoDB Database

Ensure that you have MongoDB installed and running. Create a database for your application.

 

 

Step 4: Configure Passport for Authentication

In your app.js file, configure Passport for local authentication.

const express = require('express');
const session = require('express-session');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const flash = require('connect-flash');

const app = express();

// MongoDB connection setup (mongoose)
mongoose.connect('mongodb://localhost/node-authentication', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  useCreateIndex: true,
});

// Middleware
app.use(express.urlencoded({ extended: false }));
app.use(
  session({
    secret: 'your-secret-key',
    resave: true,
    saveUninitialized: true,
  })
);
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());

// Passport Configuration
passport.use(
  new LocalStrategy((username, password, done) => {
    // Match username and password in your MongoDB
    User.findOne({ username: username }, (err, user) => {
      if (err) return done(err);
      if (!user) return done(null, false, { message: 'Incorrect username' });

      bcrypt.compare(password, user.password, (err, isMatch) => {
        if (err) return done(err);
        if (isMatch) return done(null, user);
        else return done(null, false, { message: 'Incorrect password' });
      });
    });
  })
);

passport.serializeUser((user, done) => {
  done(null, user.id);
});

passport.deserializeUser((id, done) => {
  User.findById(id, (err, user) => {
    done(err, user);
  });
});

// Routes
app.get('/', (req, res) => {
  res.send('Home Page');
});

// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

 

Step 5: Create User Model

In a separate file (e.g., models/User.js), define your User model.

const mongoose = require('mongoose');
const bcrypt = require('bcrypt');

const UserSchema = new mongoose.Schema({
  username: { type: String, unique: true, required: true },
  password: { type: String, required: true },
});

UserSchema.pre('save', function (next) {
  const user = this;
  bcrypt.hash(user.password, 10, (err, hash) => {
    if (err) return next(err);
    user.password = hash;
    next();
  });
});

const User = mongoose.model('User', UserSchema);

module.exports = User;

 

 

Step 6: Create Registration and Login Routes

Define routes for registration and login in your app.js file.

// Registration
app.get('/register', (req, res) => {
  res.render('register', { message: req.flash('signupMessage') });
});

app.post('/register', (req, res, next) => {
  passport.authenticate('local-signup', {
    successRedirect: '/profile',
    failureRedirect: '/register',
    failureFlash: true,
  })(req, res, next);
});

// Login
app.get('/login', (req, res) => {
  res.render('login', { message: req.flash('loginMessage') });
});

app.post('/login', (req, res, next) => {
  passport.authenticate('local-login', {
    successRedirect: '/profile',
    failureRedirect: '/login',
    failureFlash: true,
  })(req, res, next);
});

// Logout
app.get('/logout', (req, res) => {
  req.logout();
  res.redirect('/');
});

 

Step 7: Create Registration and Login Views

Create views for registration (views/register.ejs) and login (views/login.ejs) forms. Use a template engine like EJS.

<!-- register.ejs -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Node.js Login and Registration System - Websolutionstuff</title>
</head>
<body>
    <h2>Register</h2>
    <form action="/register" method="post">
        <input type="text" name="username" placeholder="Username" required>
        <input type="password" name="password" placeholder="Password" required>
        <button type="submit">Register</button>
    </form>
    <p><%= message %></p>
</body>
</html>
<!-- login.ejs -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Node.js Login and Registration System - Websolutionstuff</title>
</head>
<body>
    <h2>Login</h2>
    <form action="/login" method="post">
        <input type="text" name="username" placeholder="Username" required>
        <input type="password" name="password" placeholder="Password" required>
        <button type="submit">Login</button>
    </form>
    <p><%= message %></p>
</body>
</html>

 

Step 8: Create a User Profile Route

Create a route for the user profile in your app.js file.

app.get('/profile', isLoggedIn, (req, res) => {
  res.render('profile', {
    user: req.user,
  });
});

function isLoggedIn(req, res, next) {
  if (req.isAuthenticated()) return next();
  res.redirect('/login');
}

 

Step 9: Create a User Profile View

Create a view for the user profile (views/profile.ejs).

<!-- profile.ejs -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>User Profile</title>
</head>
<body>
    <h2>User Profile</h2>
    <p>Welcome, <%= user.username %>!</p>
    <a href="/logout">Logout</a>
</body>
</html>

 

Step 10: Start Your Application

In your terminal, run your Node.js application.

node app.js

 

Conclusion:

As I wrap up this tutorial, I hope you've found it as enlightening and empowering as I have. We've journeyed through the creation of a comprehensive login and registration system using Node.js, Express, and MongoDB, mastering the intricacies of user authentication along the way.

By now, you have the fundamental knowledge to implement user authentication features in your Node.js applications. You've learned how to securely register users, validate their credentials, and grant access to personalized profiles.

Thank you for joining me on this journey through the realm of user authentication in Node.js.

 


You might also like:

Recommended Post
Featured Post
How To Convert PHP Array To JSON Object
How To Convert PHP Array To JS...

In this article, we will explore the process of converting a PHP array into a JSON object. We'll achieve this transf...

Read More

Jul-08-2020

How To Disable Dates After Week In jQuery Datepicker
How To Disable Dates After Wee...

In this tutorial, we will see how to disable dates after a week in jquery datepicker. In the date picker, we can di...

Read More

Jun-29-2022

Laravel 8 Class NumberFormatter Not Found
Laravel 8 Class NumberFormatte...

In this example we will see example of laravel 8 class numberformatter not found. For numberformatter we need PHP 5...

Read More

Dec-27-2021

How to Create Trait in Laravel 10 Example
How to Create Trait in Laravel...

Hello developers! 👋 Today, let's dive into the wonderful world of Laravel 10 and explore one of its handy featu...

Read More

Feb-09-2024