Sending OTP (One-Time Password) is one of the most common tasks when building modern apps — signup verification, login security, password reset, etc.
In Node.js it’s extremely easy to implement — you just need an SMS provider (like Twilio) and library like auth-verify for generating, saving and checking user codes.
So we should install essential library (we'll only use auth-verify for whole process and we don't need any other libaries)
npm install auth-verify
And then we'll create index.js like this:
const AuthVerify = require('auth-verify');
const auth = new AuthVerify();
auth.otp.setSender({
via: 'sms',
provider: 'twilio',
apiKey: "YOUR_ACCOUNT_SID",
apiSecret "YOUR_AUTH_TOKEN",
sender: "SENDER_NAME",
mock: false // If you want to just test you can change this value to true
});
You can get accountsid and authtoken from here. And you should use your accountsid and authtoken for apiKey and apiSecret in auth-verify.
apiKey→ accountsid
apiSecret→ authtoken
And then we'll generate and save OTP code for sending with SMS
auth.otp.generate(5).set("RECIEVER_NUMBER", (err)=>{
if(err) console.log(err);
auth.otp.message({
to: "RECIEVER_NUMBER",
text: `Your OTP code is ${auth.otp.code}`
});
});
So we made OTP code and saved it to in-memory. Let's check and verify OTP code.
auth.otp.verify({check: "RECIEVER_NUMBER", code: "12345"}, (err, valid)=>{
if(err) console.log(err);
if (valid) console.log("Correct code!")'
else console.log("Incorrect code!");
});
So we finally did it!
Top comments (0)