,

Generating and sending OTP in Node.js using Javascript

Posted by

How to Send OTP in Node.js

How to Send OTP in Node.js

Sending One-Time-Password (OTP) is a common requirement for user authentication in web applications. In this article, we will discuss how to generate OTP in Node.js and send it to the user using JavaScript.

Generating OTP in Node.js

First, we need to generate a unique OTP for the user. We can use a random number or a combination of characters to create the OTP. Here’s a simple example of generating a 6-digit OTP in Node.js:

“`javascript
function generateOTP() {
const digits = ‘0123456789’;
let OTP = ”;
for (let i = 0; i < 6; i++) {
OTP += digits[Math.floor(Math.random() * 10)];
}
return OTP;
}
“`

Once we have the OTP, we can send it to the user via email, SMS, or any other communication channel.

Sending OTP in JavaScript

If you are sending the OTP via email, you can use a Node.js package like Nodemailer to send the email. Here’s an example of how to send the OTP via email using Nodemailer:

“`javascript
const nodemailer = require(‘nodemailer’);

function sendOTP(email, OTP) {
let transporter = nodemailer.createTransport({
service: ‘gmail’,
auth: {
user: ‘your-email@gmail.com’,
pass: ‘your-password’
}
});

let mailOptions = {
from: ‘your-email@gmail.com’,
to: email,
subject: ‘Your OTP’,
text: `Your OTP is: ${OTP}`
};

transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log(‘Email sent: ‘ + info.response);
}
});
}
“`

If you are sending the OTP via SMS, you can use a service provider like Twilio to send the SMS. Here’s an example of how to send the OTP via SMS using Twilio:

“`javascript
const accountSid = ‘your-account-sid’;
const authToken = ‘your-auth-token’;
const client = require(‘twilio’)(accountSid, authToken);

function sendOTP(phoneNumber, OTP) {
client.messages
.create({
body: `Your OTP is: ${OTP}`,
from: ‘your-twilio-number’,
to: phoneNumber
})
.then(message => console.log(message.sid));
}
“`

With these examples, you should now be able to generate OTP in Node.js and send it to the user using JavaScript.

0 0 votes
Article Rating
8 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@allaboutmallakhamb
10 months ago

How to merge and verify it

@om_shingare_
10 months ago

How I send it form my mail ?

@SMITSHINGALA
10 months ago

node js make rest api make send otp for registration and after login

@joydeepdas4105
10 months ago

This is not applicable for sending to gmail accounts only dummy accounts right?

@dafestanleydafe3711
10 months ago

English version will be highly appreciated. thanks in advance

@BusinessBananaShikhe
10 months ago

Aapne google sheet Scripts kese shikha batey

@HikeWithAK
10 months ago

Kya aap nodejs mein azure active directory b2c mein multi factor authentication mein OTP kaise lete hai uska tutorial bna skti ho

@purolatoronline
10 months ago

nice