A comprehensive full-stack authentication system built with Node.js, Express, React, and MongoDB. This project implements essential authentication features including user signup, login, email verification, and password reset functionality.
- Key Features
- Technology Stack
- Folder Structure
- Setup Instructions
- Environment Variables
- API Endpoints
- Mailtrap Free Plan Note
- Security Best Practices
- Future Features
- License
- ✅ User Registration with Email Verification
- ✅ User Login/Logout
- ✅ Password Reset via Email
- ✅ JWT-based Authentication
- ✅ Form Validation
- ✅ Rate Limiting
- ✅ Protected Routes
- ✅ Responsive UI
- ✅ Password Strength Meter
- ✅ Error Handling
- Node.js - JavaScript runtime environment
- Express.js - Web application framework
- MongoDB - NoSQL database
- Mongoose - Object Data Modeling (ODM) library
- JWT - JSON Web Tokens for authentication
- Bcrypt.js - Password hashing
- Mailtrap - Email testing service
- Dotenv - Environment variable management
- React - JavaScript library for building user interfaces
- Tailwind CSS - Utility-first CSS framework
- Vite - Build tool and development server
- Zustand - State management
- Framer Motion - Animation library
- React Router - Declarative routing
- Axios - HTTP client
.
├── backend/
│ ├── config/ # Configuration files
│ ├── controllers/ # Request handlers
│ ├── db/ # Database connection
│ ├── mailtrap/ # Email templates and configuration
│ ├── middleware/ # Custom middleware
│ ├── models/ # Database models
│ ├── routes/ # API routes
│ ├── utils/ # Utility functions
│ └── index.js # Entry point
├── frontend/
│ ├── src/
│ │ ├── components/ # Reusable UI components
│ │ ├── pages/ # Page components
│ │ ├── services/ # API service layer
│ │ ├── store/ # State management
│ │ ├── utils/ # Utility functions
│ │ ├── App.jsx # Main app component
│ │ └── main.jsx # Entry point
│ └── index.html # HTML template
├── .env # Environment variables
└── README.md # Project documentation
- Node.js (v14 or higher)
- MongoDB account (MongoDB Atlas or local instance)
- Mailtrap account for email testing
-
Clone the repository:
git clone <repository-url> cd mern-auth-project
-
Install backend dependencies:
npm install
-
Create a
.envfile in the root directory (see Environment Variables) -
Start the backend server:
npm run dev
-
Navigate to the frontend directory:
cd frontend -
Install frontend dependencies:
npm install
-
Start the development server:
npm run dev
-
Open your browser and visit
http://localhost:5173
Create a .env file in the root directory with the following variables:
# MongoDB connection string
MONGO_URI=your_mongodb_connection_string
# Server port
PORT=5000
# JWT secret key (use a strong random string)
JWT_SECRET=your_jwt_secret_key
# Node environment
NODE_ENV=development
# Mailtrap token for email testing
MAILTRAP_TOKEN=your_mailtrap_token
# Client URL for CORS and email links
CLIENT_URI=http://localhost:5173| Variable | Description | Required |
|---|---|---|
MONGO_URI |
MongoDB connection string | ✅ |
PORT |
Server port number | ✅ |
JWT_SECRET |
Secret key for JWT token signing | ✅ |
NODE_ENV |
Node environment (development/production) | ✅ |
MAILTRAP_TOKEN |
Mailtrap API token for email testing | ✅ |
CLIENT_URI |
Frontend application URL | ✅ |
The authentication system consists of 7 core endpoints that manage the complete user authentication lifecycle:
Purpose: Registers a new user in the system
Authentication Required: No
Flow:
- Accepts user details (name, email, password)
- Validates that all fields are provided and meet requirements
- Checks if user already exists
- Hashes the password using bcrypt
- Generates a verification token for email confirmation
- Saves user to MongoDB database
- Sends verification email to user
- Creates JWT token and sets it in an HTTP-only cookie
- Returns success response with user data (excluding password)
Purpose: Authenticates existing users and establishes a session
Authentication Required: No
Flow:
- Validates email and password are provided
- Finds user by email in database
- Compares provided password with hashed password using bcrypt
- If valid, generates JWT token and sets it in HTTP-only cookie
- Updates user's lastLogin timestamp
- Returns success response with user data
Purpose: Terminates user session
Authentication Required: No
Flow:
- Clears the JWT token cookie
- Returns success message
Purpose: Verifies if a user is currently authenticated
Authentication Required: Yes (requires valid JWT token)
Flow:
- Middleware verifies JWT token from cookie
- Finds user by ID (from token) in database
- Returns user data if found, otherwise returns error
Purpose: Confirms user's email address
Authentication Required: No
Flow:
- Accepts verification code from user
- Finds user by verification token that hasn't expired
- If valid, marks user as verified and removes verification token
- Sends welcome email to user
- Returns success response
Purpose: Initiates password reset process
Authentication Required: No
Flow:
- Accepts user's email address
- Finds user by email in database
- Generates secure reset token and expiration time
- Saves token and expiration to user document
- Sends password reset email with token link
- Returns success message
Purpose: Allows user to set a new password using reset token
Authentication Required: No
Flow:
- Accepts reset token (in URL) and new password
- Finds user by reset token that hasn't expired
- If valid, hashes new password and updates user document
- Removes reset token and expiration from user document
- Sends password reset success email
- Returns success message
POST /api/auth/signup
Content-Type: application/json
{
"name": "John Doe",
"email": "john@example.com",
"password": "SecurePassword123"
}POST /api/auth/login
Content-Type: application/json
{
"email": "john@example.com",
"password": "SecurePassword123"
}POST /api/auth/verify-email
Content-Type: application/json
{
"code": "123456"
}These endpoints work together to provide a complete authentication experience:
- Registration Flow: User signs up → Receives verification email → Verifies email → Automatically logged in
- Login Flow: User provides credentials → System validates → JWT cookie set → User authenticated
- Password Reset Flow: User requests reset → Receives email → Clicks link → Sets new password
- Session Management: Check-auth endpoint validates active sessions → Logout endpoint terminates sessions
This project uses Mailtrap for testing email functionality (such as email verification and password reset).
If you're using the Mailtrap Free Plan, emails can only be sent to the email address registered with your Mailtrap account. To send emails to other addresses, you’ll need to upgrade to a paid Mailtrap plan that supports external recipients. This configuration is perfectly fine for personal projects, testing, and local development.
- Passwords are hashed using bcrypt.js with a salt rounds of 10
- Minimum password length of 8 characters required
- Password complexity validation (uppercase, lowercase, number)
- Secure JWT secret management
- HttpOnly cookies to prevent XSS attacks
- SameSite attribute set to 'strict' to prevent CSRF attacks
- Token expiration of 7 days
- Server-side validation using express-validator
- Email format validation
- Name length validation (2-50 characters)
- Password strength validation
- Rate limiting implemented to prevent brute force attacks
- Different limits for authentication endpoints:
- 5 requests per 15 minutes for signup/login
- 3 requests per 15 minutes for password reset
- Restricted CORS to only allow requests from the client URI
- Credentials enabled for secure cookie transmission
- Sensitive data stored in environment variables
- Validation of required environment variables at startup
- Centralized error handling middleware
- Specific error messages for different error types
- Stack trace logging for debugging (in development only)
- Mongoose schema validation
- Indexes for improved query performance
- Automatic removal of sensitive data from responses
Planned improvements and upcoming features include:
- 🔐 OAuth Login (Google, GitHub, etc.)
- 📱 Two-Factor Authentication (2FA) via Email or Authenticator App
- 📊 Admin Dashboard for managing users and roles
- 📅 Session Management and device tracking
- 🕵️ Account Activity Logs (login history, IP tracking)
- 🌍 Multi-language Support (i18n)
- 💬 Email Templates with Dynamic Content
- 📦 Docker Support for easier deployment
- 🧪 Unit and Integration Tests (Jest + Supertest)
This project is licensed under the MIT License - see the LICENSE file for details.
Built with ❤️ for educational purposes