Sitemap

Handling TOTP(Time-based One Time Password) in cypress

2 min readMay 14, 2025

--

Press enter or click to view image in full size

TOTP (Time-based One-Time Password) is a type of One-Time Password (OTP) that is generated using the current time and a shared secret key between the user and the server.

In order to use Cypress for tests with TOTP (Time-based One-Time Password), you must replicate the creation and validation of the TOTP code in your tests. Usually, a TOTP library such as otplib in Node.js is used to generate the TOTP code, and Cypress commands are then used to communicate with the application.

Get Ayush Bijukchhe’s stories in your inbox

Join Medium for free to get updates from this writer.

Here’s a basic walkthrough:

  1. Install otplib for TOTP generation.
    You’ll use otplib to generate a valid TOTP based on a shared secret. You can use the mentioned command to install otplib
npm install otplib

2. Create a constant to store a secret value provided by the authenticator.

Secret key is provided by authenticator used.
        const secret = "IE3VIXXXXXXXXXXXXXXXXX" // secret key is static and given by authenticator below the QR code

3. Import authenticator from otplib.

import { authenticator } from "otplib"

4. Use generate() method to generate otp based on shared secret, this can be done by using authenticate object and calling the generate method. Created otp can be stored in any variable.

const otp = authenticator.generate(secret);
console.log(otp); //print generated OTP

Incase secret key is missed, you can get the key from API as well

--

--