Sling Academy
Home/JavaScript/Receive One-Time Passwords with the WebOTP API in JavaScript

Receive One-Time Passwords with the WebOTP API in JavaScript

Last updated: December 14, 2024

When it comes to enhancing the security of web applications, One-Time Passwords (OTPs) have become an extremely useful tool. The WebOTP API is a modern method provided by browsers to handle OTPs automatically. In this article, we'll walk through how to use the WebOTP API with JavaScript to receive OTPs seamlessly and securely.

What is WebOTP API?

The WebOTP API allows websites to programmatically obtain an OTP sent to the user’s registered phone number via SMS. It’s designed to reduce the effort required from users during the authentication process by enabling the automatic retrieval and input of OTPs. This not only enhances user experience but also reduces errors in typing out OTPs manually.

Getting Started with the WebOTP API

The WebOTP API is currently supported in modern browsers, mainly Google Chrome for Android. Before you implement the API, ensure your server is capable of sending SMS with OTP codes and that the OTP SMS follows a specific format.

The OTP SMS Format

In order for the browser to recognize the SMS and extract the OTP correctly, it must be in the following format:

ExampleCompany: Your OTP is 123456.

#123456 example.com

The text must contain a special code in the SMS body that uses the following hashtag format: #<OTP> example.com. Be sure to replace example.com with your actual domain.

How to Implement WebOTP in JavaScript

Let's dive into the code and see how we can implement WebOTP functionality using JavaScript.

Basic Usage

if ('OTPCredential' in window) {
  const input = document.querySelector('#otp-input');

  const ac = new AbortController();
  navigator.credentials.get({otp: {transport: ['sms']}, signal: ac.signal}).then(otp => {
    input.value = otp.code;
    ac.abort(); // Stop listening once the OTP is received
  }).catch(err => {
    console.error('Error while fetching OTP', err);
  });
} else {
  console.warn('WebOTP API not supported in this browser.');
}

In this example, we first check if the OTPCredential API is available on the window object, confirming that the browser supports WebOTP. We then set up an AbortController to manage the lifecycle of the API call.

The navigator.credentials.get method is used to request OTPs sent via SMS. If a valid OTP is received, it automatically fills in the #otp-input element on the page with the code.

Advanced Considerations

While the basic implementation for the WebOTP API seems straightforward, there are several advanced considerations to keep in mind.

  • Ensure that your application gracefully handles cases where the WebOTP API is not supported (either by servicing a fallback like manual OTP entry or alerting users).
  • OTPs expire quickly for security reasons, so ensure your server and client logic reflect this short validity period.
  • Carefully design your SMS format to uniquely bind to user actions, reducing the likelihood of replay attacks.

Conclusion

Utilizing the WebOTP API can significantly enhance both usability and security for web applications involving OTPs. By automating the process of receiving and inputting OTPs, you can provide a seamless user experience. Keep in mind the requirements and limitations of this API to integrate it effectively within your application.

Adopting WebOTP API is a step towards reducing friction and increasing security in your authentication workflows. Leverage this powerful tool to offer a better experience without compromising on security.

Next Article: Auto-Fill Verification Codes Using JavaScript WebOTP

Previous Article: Build VR and AR Experiences with JavaScript WebGL

Series: Web APIs – JavaScript Tutorials

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration