Node.js, Angular, MongoDB: Develop a User Registration & Login System


To create a registration and login system using Node.js and Angular, follow these steps. This guide assumes you have Node.js, Angular, and MongoDB (for storing user data) installed.

1. Set up the Backend (Node.js with Express)

a. Initialize Node.js project

  1. Create a new directory for your project and navigate into it.

    mkdir node-angular-auth
    cd node-angular-auth
  2. Initialize a new Node.js project.

    npm init -y
  3. Install necessary packages.

    npm install express mongoose bcryptjs jsonwebtoken body-parser cors

b. Create the server

  1. In the root directory, create a server.js file.
// server.js
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const bodyParser = require('body-parser');
const User = require('./models/User');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');

const app = express();
const PORT = process.env.PORT || 5000;

app.use(cors());
app.use(bodyParser.json());

// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/auth_db', { useNewUrlParser: true, useUnifiedTopology: true });

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

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

// Registration route
app.post('/api/register', async (req, res) => {
  const { username, email, password } = req.body;
  const hashedPassword = await bcrypt.hash(password, 10);

  const newUser = new User({ username, email, password: hashedPassword });

  try {
    await newUser.save();
    res.status(201).json({ message: 'User registered successfully!' });
  } catch (err) {
    res.status(500).json({ message: 'Error registering user' });
  }
});

// Login route
app.post('/api/login', async (req, res) => {
  const { email, password } = req.body;
  
  const user = await User.findOne({ email });

  if (!user) {
    return res.status(400).json({ message: 'User not found' });
  }

  const isMatch = await bcrypt.compare(password, user.password);

  if (!isMatch) {
    return res.status(400).json({ message: 'Invalid credentials' });
  }

  const token = jwt.sign({ id: user._id }, 'your_jwt_secret', { expiresIn: '1h' });

  res.json({ message: 'Login successful', token });
});

app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
  • Explanation:
    • /api/register handles the user registration with password hashing using bcryptjs.
    • /api/login verifies user credentials and returns a JWT token if successful.

2. Set up the Frontend (Angular)

a. Initialize an Angular project

  1. Install the Angular CLI (if not already installed):

    npm install -g @angular/cli
  2. Create a new Angular project.

    ng new angular-auth
    cd angular-auth
  3. Install necessary packages:

    npm install @angular/forms @angular/common
    npm install axios

b. Create Registration and Login Components

  1. Generate components for login and registration:

    ng generate component login
    ng generate component register
  2. Login Component (login.component.ts):

import { Component } from '@angular/core';
import axios from 'axios';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent {
  email: string = '';
  password: string = '';
  message: string = '';

  async onSubmit() {
    try {
      const response = await axios.post('http://localhost:5000/api/login', {
        email: this.email,
        password: this.password
      });
      this.message = 'Login successful!';
      localStorage.setItem('token', response.data.token);
    } catch (error) {
      this.message = 'Invalid credentials';
    }
  }
}
  1. Registration Component (register.component.ts):
import { Component } from '@angular/core';
import axios from 'axios';

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css']
})
export class RegisterComponent {
  username: string = '';
  email: string = '';
  password: string = '';
  message: string = '';

  async onSubmit() {
    try {
      await axios.post('http://localhost:5000/api/register', {
        username: this.username,
        email: this.email,
        password: this.password
      });
      this.message = 'User registered successfully!';
    } catch (error) {
      this.message = 'Error registering user';
    }
  }
}

c. Modify the templates (login.component.html, register.component.html)

  • Login Template:
<div>
  <h2>Login</h2>
  <form (ngSubmit)="onSubmit()">
    <label for="email">Email</label>
    <input type="email" id="email" [(ngModel)]="email" name="email" required>

    <label for="password">Password</label>
    <input type="password" id="password" [(ngModel)]="password" name="password" required>

    <button type="submit">Login</button>
  </form>
  <div>{{ message }}</div>
</div>
  • Registration Template:
<div>
  <h2>Register</h2>
  <form (ngSubmit)="onSubmit()">
    <label for="username">Username</label>
    <input type="text" id="username" [(ngModel)]="username" name="username" required>

    <label for="email">Email</label>
    <input type="email" id="email" [(ngModel)]="email" name="email" required>

    <label for="password">Password</label>
    <input type="password" id="password" [(ngModel)]="password" name="password" required>

    <button type="submit">Register</button>
  </form>
  <div>{{ message }}</div>
</div>

d. Add Routing

Edit app-routing.module.ts to include routes for login and registration components.

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { LoginComponent } from './login/login.component';
import { RegisterComponent } from './register/register.component';

const routes: Routes = [
  { path: 'login', component: LoginComponent },
  { path: 'register', component: RegisterComponent },
  { path: '', redirectTo: '/login', pathMatch: 'full' }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}

3. Run the Application

  1. Start the Node.js backend server:

    node server.js
  2. Start the Angular frontend:

    ng serve

4. Access the Application

  • Open your browser and navigate to http://localhost:4200.
  • You'll be able to register new users and log in with existing credentials.

5. Notes

  • You might want to implement better error handling, user validation, and input sanitization for a production environment.
  • The JWT token returned on login can be used for protecting routes and handling authentication in your Angular app. You can implement route guards to check if the token is available and valid.

This setup gives you a basic registration and login system with Node.js and Angular using JWT for authentication.

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete