In today’s digital landscape, secure user authentication is essential for protecting user data and application integrity. Email OTP (One-Time Password) verification enhances security by confirming user identity through time-bound codes sent to email.
- Builds a Node.js backend authentication server using industry-standard libraries
- Implements email-based OTP verification for an added security layer
- Follows a modern, scalable, and secure authentication approach suitable for real-world app.
Prerequisites
Before getting started, make sure you have the following:
- Basic understanding of Node.js and JavaScript
- Familiarity with a code editor (e.g., Visual Studio Code)
- Node.js and npm installed on your system
- Basic knowledge of REST APIs and MongoDB
Project Setup
1. Create a new project directory:
mkdir node-auth-otp
cd node-auth-otp
2. Initialize npm:
npm init -y
This will generate a package.json file to manage your project dependencies.
Dependencies
We'll utilize several popular npm packages:
- Express.js: Web framework for building Node.js applications
- Mongoose: ODM (Object Data Modeling) library for interacting with MongoDB
- Nodemailer: Email sending functionality
- bcrypt: Secure password hashing
- dotenv: Environment variable management
Install them using npm:
npm install express mongoose nodemailer bcrypt dotenv
Database Setup (MongoDB)
1. Set up a MongoDB instance (locally or on a cloud provider).
2. Create a database (e.g., auth-db) for storing user information.
Environment Variables
Create a .env file in your project root and store sensitive details like your MongoDB connection string and email credentials:
MONGODB_URI=your_mongodb_connection_string
EMAIL_HOST=your_smtp_host
EMAIL_PORT=your_smtp_port
EMAIL_USER=your_email_username
EMAIL_PASS=your_email_password
Note: Never commit your .env file to version control.
Server Implementation (server.js)
Create the server.js file, where we configure the Node.js server, connect to the database, and define authentication-related API endpoints.
1. Import Required Modules
These dependencies provide essential functionality such as server creation, database interaction, email delivery, and security.
- express is used to build RESTful APIs.
- mongoose enables structured interaction with MongoDB.
- dotenv loads environment variables securely.
2. User Schema (MongoDB)
The user schema defines how authentication-related data is stored in MongoDB.
- Stores user credentials in a structured format.
- Ensures email uniqueness for each user.
- Includes OTP and expiration fields for verification.
3. Connect to MongoDB
This establishes a secure connection between the Node.js application and MongoDB.
- Uses environment variables for secure configuration.
- Enables modern MongoDB connection features.
- Logs connection status for debugging.
4. Initialize Express App
This sets up the Express application and enables JSON request handling.
- Initializes the Express server and parses incoming JSON request bodies.
- Prepares the app for API route definitions.
5. Generate OTP
This function creates a random six-digit OTP for verification.
- Generates a numeric 6-digit OTP
- Ensures randomness for security
- Can be replaced with a dedicated OTP library if needed
6. Send OTP via Email
This function sends the generated OTP to the user’s email address.
- Uses Nodemailer with SMTP configuration
- Sends a time-bound OTP for security
- Supports easy customization of email content
7. User Registration with OTP
This endpoint registers a new user and initiates email-based OTP verification.
- Hashes passwords securely using bcrypt.
- Stores OTP with an expiration time.
- Sends OTP immediately after successful registration.
8. OTP Verification Endpoint (Placeholder)
This endpoint will validate the OTP entered by the user.
- Intended to verify submitted OTP values.
- Should handle expiration and mismatch cases.
- Clears OTP data after successful verification.
Expected Verification Flow:
- Find the user by email.
- Compare submitted OTP with stored OTP.
- Validate OTP expiration and remove it on success.
9. Start the Server
This launches the backend server and listens for incoming requests.
- Starts the application on the defined port.
- Uses environment variables for flexibility.
- Confirms server status via console logging.
Complete server.js File
Here is the complete server.js file including full implementation:
Security & Implementation Considerations
These points highlight essential steps and best practices to make the authentication system reliable and production-ready.
- Replace placeholder logic with a secure OTP generation and reliable email delivery implementation.
- Implement the /verify-otp endpoint to validate OTPs and check expiration time.
- Add robust error handling and proper input validation throughout the codebase.
- Apply production-level security practices such as rate limiting, logging, and secure configurations.