Creating the Server

Create a file name it as server.js and add the following code:

HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>OTP Verification</title>
    <style>
        body {
            font-family: Arial, sans-serif;
        }
        .container {
            max-width: 400px;
            margin: 0 auto;
            padding: 20px;
            border: 1px solid #ccc;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        input[type="text"], input[type="password"], button {
            width: 100%;
            padding: 10px;
            margin-bottom: 10px;
            box-sizing: border-box;
        }
        button {
            background-color: #007bff;
            color: #fff;
            border: none;
            cursor: pointer;
        }
        button:hover {
            background-color: #0056b3;
        }
        .message {
            margin-top: 10px;
            text-align: center;
            color: red;
        }
    </style>
</head>
<body>
    <div class="container">
        <h2>OTP Verification</h2>
        <input type="email" id="email" placeholder="Enter your email">
        <button onclick="generateOTP()">Generate OTP</button>
        <input type="text" id="otp" placeholder="Enter OTP">
        <button onclick="verifyOTP()">Verify OTP</button>
        <p class="message" id="response"></p>
    </div>

    <script>
        async function generateOTP() {
            const email = document.getElementById('email').value;

            const response = await fetch('http://localhost:3000/generate-otp', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ email })
            });

            const result = await response.text();
            document.getElementById('response').innerText = result;
        }

        async function verifyOTP() {
            const email = document.getElementById('email').value;
            const otp = document.getElementById('otp').value;

            const response = await fetch('http://localhost:3000/verify-otp', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ email, otp })
            });

            const result = await response.text();
            document.getElementById('response').innerText = result;
        }
    </script>
</body>
</html>
JavaScript
// server.js
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const otpGenerator = require('otp-generator');
const nodemailer = require('nodemailer');
const cors = require('cors');
const app = express();
const PORT = process.env.PORT || 3000;

app.use(bodyParser.json());
app.use(cors());
// MongoDB connection
mongoose.connect('mongodb+srv://<username>:<password>@cluster0.d6t5od6.mongodb.net/', { useNewUrlParser: true, useUnifiedTopology: true });

const db = mongoose.connection;

db.on('error', (err) => {
    console.error('MongoDB connection error:', err);
});

db.once('open', () => {
    console.log('Connected to MongoDB');
});

// Define schema and model for OTP
const otpSchema = new mongoose.Schema({
    email: String,
    otp: String,
    createdAt: { type: Date, expires: '5m', default: Date.now }
});

const OTP = mongoose.model('OTP', otpSchema);

// Generate OTP and send email
app.post('/generate-otp', async (req, res) => {
    const { email } = req.body;

    const otp = otpGenerator.generate(6, { digits: true, alphabets: false, upperCase: false, specialChars: false });

    try {
        await OTP.create({ email, otp });

        // Send OTP via email (replace with your email sending logic)
        const transporter = nodemailer.createTransport({
            service: 'gmail',
            auth: {
                user: 'your-mail@gmail.com',
                pass: 'your-app-password'
            }
        });

        await transporter.sendMail({
            from: 'your-mail@gmail.com',
            to: email,
            subject: 'OTP Verification',
            text: `Your OTP for verification is: ${otp}`
        });

        res.status(200).send('OTP sent successfully');
    } catch (error) {
        console.error(error);
        res.status(500).send('Error sending OTP');
    }
});

// Verify OTP
app.post('/verify-otp', async (req, res) => {
    const { email, otp } = req.body;

    try {
        const otpRecord = await OTP.findOne({ email, otp }).exec();

        if (otpRecord) {
            res.status(200).send('OTP verified successfully');
        } else {
            res.status(400).send('Invalid OTP');
        }
    } catch (error) {
        console.error(error);
        res.status(500).send('Error verifying OTP');
    }
});

app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});

Building an OTP Verification System with Node.js and MongoDB

In the present digital world, Securing your website or internet could be very crucial. One manner to increase protection is by using One Time Password (OTP) for the verification system. This will help you to steady your software and defend your website from unauthorized get entry. This article will help you create an OTP verification device, which you can use in your upcoming initiatives. This venture was created using Nodejs and MongoDB, which is a completely famous technology in net improvement.

Similar Reads

What’s OTP Verification?

OTP verification adds an extra layer of security to your application. When you log in or perform sensitive actions online this will help you to not allow anyone without your permission. Instead of using the same password whenever you get hold of a completely unique code for your cellphone or e-mail that you need to go into to verify your identity. This code is legitimate simplest to use and expires after a short time which makes it very steady....

Why Node.js and MongoDB?

Node.Js is a powerful JavaScript runtime that builds rapid and scalable net programs. MongoDB is a versatile and clean-to-use NoSQL database that stores our information in a JSON-like layout. Together, they make a terrific aggregate for building dynamic and efficient systems....

Project Structure and Dependency:

Here is the project structure which you have to follow to make otp verification system. You can also use another front-end frameworks to give a nice look, But for simplicity I am using HTML page....

Steps to Create OTP Verification System

Step 1: Setting Up the Project...

Step 1: Setting Up the Project

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

Step 2: Creating the Server

Create a file name it as server.js and add the following code:...

Step 3: Running the Server

Run the server using the following command:...

Step 4: Testing the Endpoints

You can now test the OTP generation and verification endpoints using a tool like Postman. You can also try it using the start server of HTML or by making HTTP requests from your frontend application....

Output-

...

Conclusion

In conclusion, building an OTP verification gadget with Node.Js and MongoDB adds a essential layer of safety to web programs. By requiring customers to verify their identity with a completely unique, one-time code, we are able to substantially reduce the hazard of unauthorized access and protect sensitive consumer information. With the technology used in this utility, including Node.Js, Express.Js, MongoDB, otp-generator, and nodemailer. Now your Otp verification system is ready to use. You can also add this feature to your application for securing your application. This application will help you to add security to you upcoming application. It also ensure that your application will not affected by other users/middle-man....

FAQs

Why is OTP verification important for web applications?...