DEV Community

Cover image for Project Four: One Time Password

Posted on

Project Four: One Time Password

Short one time passwords are an easy and cheap way to increase security of a service. They are usually a part of multi-factor authentication being an additional step after login and password or used on its own to verify potentially destructive actions.

You probably encounter them on a daily basis and are quite familiar with the flow. How about implementing a field for an OTP code today?

One Time Password Input: requirements and recipe

As a user I want to be able to enter OTP code, so that I could verify my identity easily.

There are several types of OTP codes: they vary based on the delivery method and their implementation. Generally speaking it's a short numeric code that is either send to a device - or generated by an authenticator app.

Inputs can look very differently, for example like this:

Six numbers with a dashed underscore below each one

Appearance of the input field is up to you, but there are some generic requirements:


  1. Input should only allow numeric values
  2. Input should be limited to a certain amount of digits (e.g. 6)
  3. User should be able to input the code by pressing numbers on the keyboard
  4. User should be able to copy and paste the code
  5. User should be able to use built-in code autocomplete (e.g. from 1Password or on mobile using sms reading function)
  6. There should be only one input for the whole code


  1. Create a single text input
  2. Set input properties according to requirements
  3. Style the input to look like it has multiple "cells"
  4. Add a dash of JavaScript to mimic focusing on each cell
  5. Sprinkle with your favourite framework


There are multiple ways how you could implement code "sections": for example by layering HTML elements or using inline SVG.

You might stumble upon implementations with multiple inputs - one per digit, but those implementations don't allow reading SMS or using autocomplete.

Hard mode: OTP code generator

Now that you've mastered the art of CSS how about implementing universal script to generate said OTP codes?

It's not as hard as you might think and you can do it using WebCrypto API: all you need is an official specification.

I suggest using Google Authenticator app, just keep in mind that OTP specification and example implementation assumes that you have a raw secret while Google Authenticator link/QR code takes the secret base32 encoded (that took me an embarrassingly long time to figure out).

Hope you'll have fun!

Share your creations and feedback and see you tomorrow!

Liked the idea a lot and would love to have it all year long?

Buy Me A Coffee

Top comments (0)