A modern, production-ready authentication system built with React, Node.js, Express, Prisma, and MongoDB. Features a beautiful, customizable UI with enterprise-grade security and comprehensive user management.
- JWT-based Authentication - Secure token-based authentication system
- Email Verification - OTP-based email verification with configurable settings
- Password Reset - Secure password reset via email tokens
- Password Hashing - bcrypt with salt rounds for secure password storage
- Protected Routes - Client-side route protection with authentication guards
- Token Refresh - Automatic token validation and refresh handling
- Responsive Design - Mobile-first approach with perfect cross-device compatibility
- Customizable Theme System - Complete design system with CSS custom properties
- Smooth Animations - Micro-interactions and transitions for enhanced UX
- Loading States - Comprehensive loading indicators and skeleton screens
- Error Handling - User-friendly error messages and validation feedback
- Accessibility - WCAG compliant with proper ARIA labels and keyboard navigation
- SMTP Integration - Configurable email service with Gmail support
- Beautiful Email Templates - HTML email templates for all communications
- Email Types:
- Welcome emails
- Email verification with OTP
- Password reset links
- Account notifications
- TypeScript Support - Full type safety across the entire application
- Hot Reload - Fast development with Vite and Node.js watch mode
- Database Management - Prisma ORM with MongoDB integration
- Environment Configuration - Comprehensive environment variable setup
- Error Logging - Detailed server-side error logging and debugging
- Database Tools - Built-in database management and cleanup scripts
- React 19 with TypeScript
- Vite for blazing-fast development and building
- Tailwind CSS for utility-first styling
- React Router for client-side routing
- Axios for HTTP requests with interceptors
- Lucide React for beautiful icons
- Node.js with Express.js
- Prisma ORM for database operations
- MongoDB as the primary database
- JWT for authentication tokens
- Nodemailer for email services
- bcryptjs for password hashing
Before you begin, ensure you have the following installed:
- Node.js (v18 or higher) - Download here
- npm or yarn package manager
- MongoDB database (local or cloud) - MongoDB Atlas
- Git for version control
- Gmail account (for email services) or other SMTP provider
git clone https://github.com/tarinagarwal/MongoDB-Auth
cd MongoDB-Authcd server
npm installcd ../client
npm installCreate a .env file in the server directory:
cd server
cp .env.example .envConfigure your .env file with the following variables:
# Database Configuration
DATABASE_URL="mongodb+srv://<username>:<password>@<cluster-url>/<dbname>?retryWrites=true&w=majority&appName=<clusterName>"
# JWT Configuration
JWT_SECRET="your-super-secret-jwt-key-change-this-in-production"
JWT_EXPIRES_IN="7d"
# Email Configuration
EMAIL_VERIFICATION_ENABLED=true
SMTP_HOST="smtp.gmail.com"
SMTP_PORT=587
SMTP_USER="your-email@gmail.com"
SMTP_PASS="your-app-password"
FROM_EMAIL="your-email"
FROM_NAME="Your App Name"
# Server Configuration
PORT=5000
NODE_ENV=development
# Frontend URL (for email links)
FRONTEND_URL="http://localhost:5173"Create a .env file in the client directory:
cd ../client
cp .env.example .envConfigure your client .env file:
# API Configuration
VITE_API_BASE_URL=http://localhost:5000/apicd server
npm run db:generatenpm run db:pushnpm run db:studio- Enable 2-Factor Authentication on your Gmail account
- Go to Google App Passwords
- Generate a new app password for "Mail"
- Use this app password in your
SMTP_PASSenvironment variable
cd server
npm startThe server will start on http://localhost:5000
cd client
npm run devThe client will start on http://localhost:5173
This is a complete authentication template designed to be the foundation for your next project. Here's how to get started:
- User registration with email verification
- Secure login/logout functionality
- Password reset via email
- JWT-based session management
- Protected route system
- User profile management
- Landing Page - Customizable homepage template
- Authentication Pages - Login, Signup, Verify Email, Reset Password
- Profile Page - User account management
- 404 Page - Error handling
- Responsive Navbar - With user dropdown and mobile menu
- Protected Route Wrapper - Automatic authentication checks
- Loading Components - Spinners and loading states
- Scroll Components - Scroll to top functionality
// App.tsx is already structured with:
<Routes>
{/* Public Routes - Anyone can access */}
<Route path="/" element={<LandingPage />} />
<Route path="/login" element={<LoginPage />} />
<Route path="/signup" element={<SignupPage />} />
{/* Protected Routes - Requires authentication */}
<Route
path="/profile"
element={
<ProtectedRoute>
<ProfilePage />
</ProtectedRoute>
}
/>
{/* Add your protected routes here */}
</Routes>The navbar includes placeholder links that you can customize:
- Home - Links to landing page
- About - Ready for your about page
- Services - Ready for your services page
- Contact - Ready for your contact page
Replace the template landing page content with your project:
// client/src/pages/LandingPage.tsx
// Replace the hero section, features, and content with your project details// client/src/components/Navbar.tsx
const navigationLinks = [
{ name: "Home", href: "/", icon: Home },
{ name: "Your Page", href: "/your-page", icon: YourIcon },
// Add your actual navigation items
];// In App.tsx, add your protected routes:
<Route
path="/dashboard"
element={
<ProtectedRoute>
<YourDashboard />
</ProtectedRoute>
}
/>// client/tailwind.config.js
colors: {
brand: {
500: "#your-primary-color", // Change to your brand color
600: "#your-primary-hover",
// ... customize all brand colors
}
}- Change "Auth Template" to your project name in:
client/src/components/Navbar.tsxclient/index.html(title)- Email templates in
server/utils/emailService.js - Environment variables (
FROM_NAME, etc.)
- Modular Components - Each component has a single responsibility
- Consistent Theming - Semantic CSS classes for easy customization
- Type Safety - Full TypeScript implementation
- Responsive Design - Mobile-first approach
- Security First - Enterprise-grade authentication
- Developer Experience - Hot reload, error handling, loading states
- Replace Landing Page - Update with your project's value proposition
- Add Your Pages - Create pages specific to your application
- Update Navigation - Replace placeholder links with real ones
- Customize Theme - Match your brand colors and styling
- Configure Email - Update email templates with your branding
- Add Features - Build your core application features
- Deploy - Use the included deployment guides
This template gives you a production-ready foundation so you can focus on building your unique features instead of authentication boilerplate!
- User visits
/signupand fills out the registration form - If email verification is enabled:
- User receives a 6-digit OTP via email
- User enters OTP on
/verify-emailpage - Account is activated after successful verification
- If email verification is disabled:
- User is automatically logged in after registration
- User logs in via
/loginwith email/username and password - Server validates credentials and returns JWT token
- Token is stored in localStorage and used for authenticated requests
- Protected routes automatically redirect unauthenticated users to login
- User clicks "Forgot Password" on login page
- User enters email address on
/forgot-password - System sends password reset email with secure token
- User clicks email link and is redirected to
/reset-password/:token - User enters new password and account is updated
The application uses a comprehensive theme system built with Tailwind CSS. You can customize the entire appearance by modifying the theme configuration:
Edit client/tailwind.config.js to change the color palette:
colors: {
brand: {
500: "#your-primary-color", // Main brand color
600: "#your-primary-hover", // Primary hover color
// ... other shades
},
// ... other color configurations
}Modify font families and sizes in the same config file:
fontFamily: {
primary: ["Your-Font", "system-ui", "sans-serif"],
},The theme system uses semantic CSS classes in client/src/index.css. Modify these classes to change component appearances:
.theme-btn-primary {
/* Your custom button styles */
}
.theme-card {
/* Your custom card styles */
}Email templates are located in server/utils/emailService.js. Each email function contains HTML templates that you can customize:
sendVerificationEmail()- Email verification templatesendWelcomeEmail()- Welcome email templatesendPasswordResetEmail()- Password reset template
Set EMAIL_VERIFICATION_ENABLED=false in your server .env file to allow immediate login after registration.
Modify JWT_EXPIRES_IN in your server .env file (e.g., "1d", "7d", "30d").
- bcrypt Hashing - Passwords are hashed with salt rounds
- Minimum Length - 6 character minimum password requirement
- Secure Reset - Time-limited password reset tokens
- JWT Tokens - Stateless authentication with configurable expiration
- Secure Storage - Tokens stored in localStorage with automatic cleanup
- Token Validation - Server-side token verification on protected routes
- OTP Verification - 6-digit one-time passwords for email verification
- Time-Limited Tokens - All email tokens expire after set time periods
- Secure Links - Password reset links contain cryptographically secure tokens
- Client-Side Validation - Real-time form validation with user feedback
- Server-Side Validation - Comprehensive input sanitization and validation
- SQL Injection Protection - Prisma ORM provides built-in protection
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
- Verify MongoDB connection string in
.env - Ensure database is running and accessible
- Check network connectivity for cloud databases
- Verify SMTP credentials in
.env - Check Gmail app password setup
- Ensure 2FA is enabled on Gmail account
- Check spam/junk folders
- Clear node_modules and reinstall dependencies
- Ensure Node.js version compatibility (v18+)
- Check for TypeScript errors in the console
- Verify JWT_SECRET is set in server
.env - Check token expiration settings
- Clear localStorage and try logging in again
If you encounter issues:
- Check the troubleshooting section above
- Review server logs for error messages
- Verify all environment variables are set correctly
- Ensure all dependencies are installed
- Reach me out at tarinagarwal@gmail.com
Built with β€οΈ for the developer community
Happy coding! π