Build Advanced MERN Auth: 2FA, Email Verification, Cookies, Sessions, and JWT with Node.js & Next.js

Updated: January 22, 2025

TechWithEmma


Summary

This tutorial guides viewers through building a robust authentication system using Node.js and Express, covering essential features like access tokens, two-factor authentication, email verification, and password reset. The video provides a comprehensive overview of setting up various components such as error handling middleware, user registration/validation, JWT token management, and MongoDB integration. Additionally, the tutorial explores implementing multi-factor authentication, session management, log out functionality, and token refresh processes, offering a practical and in-depth approach to enhancing security and user experience in web applications.


Project Overview

Learn to build a production-ready advanced authentication system using Node.js and Express. The system includes features like access tokens, refresh tokens, two-factor authentication, email verification, password reset, sending emails, managing sections, and structuring code for scalability.

User Account Creation

Users can create an account and receive a confirmation link via email. Tokens are sent to the browser for device login tracking and session management. Two-factor authentication can be enabled for added security.

Email Verification and Password Reset

After logging in, users are prompted to verify two-factor authentication. Email verification and password reset functionalities are demonstrated.

Setting up the Project Directory

Creation of a new directory and installation of necessary packages using npm. Configuration of TypeScript and installation of dependencies like cors, dotenv, dotenv-safe, express, jsonwebtoken, mongoose, passport, bcrypt, and others.

Setting up the TS Config

Updating the tsconfig.json file with project settings including specifying the source directory, output directory, excluding node_modules during compilation, and setting up compilerOptions.

Database Setup with MongoDB Atlas

Creating a database on MongoDB Atlas, obtaining connection credentials, configuring the database URL in the project, and connecting to the database from the application.

Error Handling Middleware

Implementation of error handling middleware to catch and handle errors in the application. Creation of custom error classes to represent different types of errors like bad request, unauthorized access, and internal server errors.

Authentication Controllers and Routes

Creation of modules, routes, services, controllers, and validation for user registration. Setting up routes in the application and handling user input data like name, email, password, and user agent.

Setting Up Schemas for Validation

Creating schemas for validating user input data like email, password, and user agent. Reusing the schemas for different purposes such as registration and login.

Creating User Models and Preferences

Setting up user models and preferences including fields for email, password, two-factor authentication, and preferences like email notifications. Defining schema structures using Mongoose in MongoDB.

Handling User Authentication and Sessions

Managing user authentication by generating verification codes, creating sessions, and implementing token-based authentication. Working with JWT tokens, creating utility functions for token signing, and refreshing access tokens.

Handling Error Instances and Responses

Implementing error handling by creating functions to handle different types of errors and respond accordingly. Setting up error instances and providing appropriate responses to errors in the API.

Setting Options for JWT Sign

Setting the option type for JWT signing and displaying the available options.

Signing the JWT

Signing the JWT with default sign options and closing the token for use in the refresh token service.

Verification of JWT

Verifying the JWT token before usage and setting the token option.

Refreshing JWT

Refreshing the JWT token with the refresh token and setting the expiration date.

Email Verification

Implementing email verification functionality and updating user details upon verification.

Sending Verification Email

Setting up and sending a verification email to the user's email address for account confirmation.

Resetting Password

Implementing the functionality to reset a user's password with email verification code for security.

Setting Up Access Control

Setting up access control by clearing the access and running a post request with a password reset and verification code.

Setting Up Protected Routes with Passport JWT

Setting up protected routes using Passport JWT to handle session IDs and create a strategy for JWT authentication.

Logging Out User Sessions

Implementing a logout API to clear user sessions and handling log out functionality in the controller and service.

Retrieving User Sessions

Creating an API to retrieve user sessions, getting all sessions, and getting a single session using the service and controller.

Deleting User Sessions

Implementing an API to delete user sessions dynamically with controllers and services, including checking and handling session deletion.

Setting Up Two-Factor Authentication (2FA)

Establishing the groundwork for 2FA with JWT, generating a secret key, creating a QR code, and setting up the MFA validator for verification.

Verifying Two-Factor Authentication

Implementing an API to verify the 2FA code, enabling 2FA for users, and handling successful verification in the service.

Implementing User Authentication

The process of implementing user authentication in the backend by setting up endpoints for user login, MFA verification, password reset, and registration.

Setting Up Frontend with Next.js

Setting up the frontend using Next.js, initializing Shanty, and setting up the project structure with routes for different authentication pages like sign up, password reset, and login forms.

Fixing Email Error

Identified and resolved an error related to email matching during signup and sending. Ensured correct email usage for sending and signing in.

Resetting Password

Implemented password reset functionality by creating a separate file for handling password reset. Updated reset page and form with necessary components for password recovery.

Handling Account Confirmation

Implemented account confirmation functionality by creating a separate page and handling email verification. Verified user email upon account confirmation for security purposes.

Creating Protected Routes

Implemented a system to restrict access to certain routes based on user login status. Implemented middleware to handle protected routes and redirect users accordingly.

Setting up Context Provider

Set up a context provider in the application to manage user authentication data and access control. Created context for managing user authentication state and access permissions.

Enabling Multi-Factor Authentication (MFA)

Implemented functionality to enable MFA using QR code scanning and one-time passwords. Verified MFA setup and added features for code verification.

Revoking MFA Access

Implemented the ability to revoke MFA access for users. Created functions to remove MFA settings and handle API calls for revoking access.

Implementing MFA Verification

The chapter covers the implementation of Multi-Factor Authentication verification process for logging in. It includes setting up MFA data types, creating separate files for verification, handling email addresses, and testing the verification process.

Session Management

This section focuses on session management within the application. It involves handling session data, displaying session information, managing sessions, and handling session deletion with user agents and expiration dates.

Logging Out Functionality

The chapter discusses the implementation of logging out functionality in the application. It covers setting up the log out dialog, handling the log out mutation function, changing themes, and testing the log out feature.

Token Refresh and Authorization

This chapter delves into token refresh and authorization processes in the application. It includes handling token expiration, updating tokens, intercepting unauthorized requests, and ensuring seamless authorization throughout the application.


FAQ

Q: What features are included in the advanced authentication system built using Node.js and Express?

A: Features included in the system are access tokens, refresh tokens, two-factor authentication, email verification, password reset, sending emails, managing sections, and structuring code for scalability.

Q: How is two-factor authentication implemented in the system?

A: Two-factor authentication can be enabled for added security, and users are prompted to verify it after logging in. Users can also set up 2FA using QR code scanning and one-time passwords.

Q: What packages are necessary for building the authentication system using Node.js and Express?

A: Packages like cors, dotenv, dotenv-safe, express, jsonwebtoken, mongoose, passport, bcrypt, among others, are used in the project.

Q: How is error handling managed in the application?

A: Error handling middleware is implemented to catch and handle errors. Custom error classes are created to represent different types of errors like bad requests, unauthorized access, and internal server errors.

Q: Describe the process of setting up user authentication in the backend.

A: Endpoints for user login, two-factor authentication verification, password reset, and user registration are set up in the backend. Token-based authentication is implemented using JWT tokens.

Q: What is the role of JWT tokens in the authentication process?

A: JWT tokens are used for user authentication by generating verification codes, sessions, and handling token-based authentication. Utility functions are created for token signing and refreshing access tokens.

Q: How is access control enforced in the system?

A: Access control is enforced by setting up protected routes using Passport JWT for handling session IDs and creating a strategy for JWT authentication. Middleware is implemented to handle protected routes.

Q: What functionalities are provided for user session management?

A: Functionalities include retrieving user sessions, deleting sessions dynamically, and implementing a logout API to clear user sessions. Context providers are set up to manage user authentication data.

Q: Explain the process of implementing Multi-Factor Authentication (MFA) in the application.

A: MFA setup involves generating a secret key, creating a QR code, enabling 2FA for users, and handling verification codes. Features for revoking MFA access are also implemented.

Q: What role does session management play in the application?

A: Session management involves handling session data, displaying session information, managing sessions, and ensuring secure session deletion with user agents and expiration dates.

Logo

Get your own AI Agent Today

Thousands of businesses worldwide are using Chaindesk Generative AI platform.
Don't get left behind - start building your own custom AI chatbot now!