Using WebOtp API in Nextjs / React

18 / Jul / 2023 by Anshul Mittal 0 comments

In today’s applications, we have observed that when logging in or performing sensitive tasks online, we receive One time passwords on our registered phone numbers to secure this activity. But as a user, it is a bit vexing to remember that code and then type that into the required fields. At the same time, we may be able to auto-detect these SMS on native apps for Android or ios, Web-based applications users do not. But this is now possible with the help of WebOTP API; it gives websites the ability to programmatically obtain the one-time password from an SMS message and automatically fill the form for users with just one tap without switching apps.

How does it work?

Using the WebOTP API consists of three parts:

  • A properly annotated <input> tag
  • JavaScript in your web app
  • Formatted message text sent via SMS.

A Properly Annotated Input Tag

> Add autocomplete="one-time-code" to the <input> tag where the OTP should be entered.

Example: <input autocomplete='one-time-code' />

Javascript Code

Useeffect code

Make sure to use ac.abort() after completion of the login process / running out of Otp entering time.

We can wrap our code with if (‘OTPCredential’ in window){ /* Code */} to use feature detection of WebOTP API.

SMS Format

> The message begins with (optional) human-readable text that contains a four to ten-character alphanumeric string with at least one number leaving the last line for the URL and the OTP.
> The domain part of the URL of the website that invoked the API must be preceded by @.
> The URL must contain a pound sign (‘#’) followed by the OTP.

Example :

Your OTP is: 123456.

@www.yourdomain.com #123456

Now that our code is ready, Let’s say you have entered the correct login details; you will receive an OTP on your registered SMS. To test this code, you can send an SMS from another phone to the phone where you are testing.

Make sure that:

  1. RCS is off.
  2. That phone number should not be on your contacts list.
  3. The SMS format should be valid with the correct domain name.

Once you receive the SMS, You will get a popup asking you to allow the web app to read your received SMS, If the SMS format is correct, your business logic should work as expected.

Comment down in the comment section if you have any questions related to the process.

FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *