DEV Community

Cover image for How to use API based providers for sending OTP in Node.js
Jahongir Sobirov
Jahongir Sobirov

Posted on

How to use API based providers for sending OTP in Node.js

For using API based providers you should have API key or API secret. And in this post I'll show you how to use Resend API provider for sending OTP codes to clients. For this we need only single library which named auth-verify. You can install it from NPM

npm install auth-verify
Enter fullscreen mode Exit fullscreen mode

Setup

Firt of all we should configure API provider to our app:

const AuthVerify = require('auth-verify');
const auth = new AuthVerify();

// configure the otp sender
auth.otp.sender({
   via: 'email',
   service: 'api',
   apiService: 'resend', 
   apiKey: 'YOUR_API_KEY_HERE'
});
Enter fullscreen mode Exit fullscreen mode

You can use also Mailgun, Sendgrid. Just change the apiService

Sending the OTP code

For sending OTP code to the client we'll use send() method.

await auth.otp.send("johndoe@example.com", {
   otpLen: 5, // length of otp codes (default: 6)
   subject: "Account verification",
   text: `Your OTP code is ${auth.otp.code}`
});
Enter fullscreen mode Exit fullscreen mode

Verify the OTP code

For verifying OTP code which is provided by client we'll use verify() method.

const valid = await auth.otp.verify("johndoe@example.com", "12345");
if(valid) console.log('User verified!');
else console.log('Invalid code!');
Enter fullscreen mode Exit fullscreen mode

Top comments (0)