Skip to content
  • Testing
  • Playwright

Test passwordless flows

This guide shows you how to automate passwordless authentication testing with Playwright by intercepting the one-time code email. Learn more about testing passwordless flows with Kinde.

The examples use Mailosaur, but any inbox service with an API for reading emails programmatically (for example MailSlurp or Mailtrap) works the same way: give each test a unique inbox, wait for the code email, extract the code, and enter it in the form.

Kinde one-time codes are always 6 digits, are generated fresh for every request, and expire after 2 hours (120 minutes) by default (configurable per environment). There is no static “test code”: intercepting the real email is the supported way to automate these flows.

Keep OTP tests lean

Link to this section

Waiting on real email delivery is the slowest and most failure-prone part of any test suite. Tests that sign up or sign in through a hosted screen that sends a code need an inbox: passwordless sign-up, passwordless sign-in, and Email + password sign-up (new users verify their email with a code). Cover those with a small number of smoke tests and authenticate the rest of your suite another way:

  • Reuse authenticated state with Playwright’s storageState (see Test authenticated features).
  • Create a pre-verified Email + password test user with the Management API and sign in with it. The user’s email is already marked as verified, so no code is sent. See Create a pre-verified test user with the Management API, which includes a Playwright fixture that creates a fresh user per test and deletes it afterwards.

Setup Mailosaur

Link to this section
  1. Sign in to your Mailosaur account.

  2. Copy the Server ID from the dashboard.

  3. Go to API Keys > select Create standard key and copy the value.

  4. Install the Mailosaur client and environment variable dependencies in your Playwright project:

    Terminal window
    npm i -D mailosaur dotenv @types/node
  5. Add the following to your .env file:

    # ... other environment variables ...
    MAILOSAUR_API_KEY=your-api-key
    MAILOSAUR_SERVER_ID=your-server-id
  6. Create a helper utility file tests/utils/mailosaur.ts:

    Terminal window
    mkdir -p tests/utils
    touch tests/utils/mailosaur.ts
  7. Add the following code to mailosaur.ts:

    tests/utils/mailosaur.ts
    import MailosaurClient from "mailosaur"
    import "dotenv/config"
    const mailosaur = new MailosaurClient(process.env.MAILOSAUR_API_KEY!)
    const serverId = process.env.MAILOSAUR_SERVER_ID!
    export async function getOTPFromEmail(
    email: string,
    receivedAfter?: Date,
    ): Promise<{
    emailId: string | undefined
    otpCode: string
    deleteEmail: () => Promise<void>
    }> {
    // Pass receivedAfter when a test reuses an inbox across runs, so you
    // never pick up a stale code from a previous run's email.
    const message = await mailosaur.messages.get(
    serverId,
    { sentTo: email },
    { receivedAfter },
    )
    // Kinde codes are always exactly 6 digits. Strip HTML comments first so
    // render timestamps in non-production environments are not matched.
    const cleanTextBody = message.text?.body?.replace(/<!--[\s\S]*?-->/g, "")
    const otpMatch = cleanTextBody?.match(/\b(\d{6})\b/)
    const otpCode = otpMatch?.[1] ?? message.html?.codes?.[0]?.value
    if (!otpCode) {
    throw new Error("Could not extract OTP code from email")
    }
    return {
    emailId: message.id,
    otpCode,
    deleteEmail: async () => {
    await mailosaur.messages.del(message.id!)
    },
    }
    }

Write resilient tests

Link to this section

Two things to know before writing selectors against Kinde’s hosted pages:

  • The screens around the code step evolve. For example, enabling passkeys adds a passkey option to the sign-in screen, and passing login_hint can pre-fill (or skip) the email step. Prefer role and label-based selectors (getByRole, getByLabel) or Kinde’s stable form field attributes, which use a p_ name prefix such as input[name="p_email"], over positional selectors, and keep the authentication methods on your test environment limited to the ones you are actually testing.
  • The code entry step itself is stable. The code input is input[name="p_confirmation_code"] (labelled “Code”) and accepts exactly 6 digits.

Test passwordless sign-up flow

Link to this section

To test the passwordless sign-up flow, enable the Email + code option in authentication methods in your Kinde application.

  1. Create a new test file:

    Terminal window
    touch tests/passwordless-signup.spec.ts
  2. Add the following code:

    tests/passwordless-signup.spec.ts
    import { test, expect } from "@playwright/test"
    import { getOTPFromEmail } from "./utils/mailosaur"
    const serverId = process.env.MAILOSAUR_SERVER_ID!
    test.describe("Passwordless Authentication Flows", () => {
    test("user can sign up with email and code", async ({ page }) => {
    // Generate unique email for this test run
    const timestamp = Date.now()
    const testEmail = `test-${timestamp}@${serverId}.mailosaur.net`
    await page.goto(process.env.TEST_APP_URL!)
    await page.click('[data-testid="sign-up-button"]')
    // Wait for Kinde sign-up page (uses KINDE_ISSUER_URL to support custom domains)
    const authUrl = new URL(process.env.KINDE_ISSUER_URL!)
    await expect(page).toHaveURL(
    new RegExp(authUrl.hostname.replaceAll(".", "\\.")),
    )
    // Fill sign-up form
    await page.fill('input[name="p_first_name"]', "John")
    await page.fill('input[name="p_last_name"]', "Doe")
    await page.fill('input[name="p_email"]', testEmail)
    // Uncomment the line below if Clickwrap agreements (Terms & Conditions) are enabled in your Kinde environment:
    // await page.check('input[name="p_has_clickwrap_accepted"]')
    await page.click('button[type="submit"]')
    // Wait for OTP email and extract code
    const { otpCode, deleteEmail } = await getOTPFromEmail(testEmail)
    try {
    // Enter OTP
    await page.fill('input[name="p_confirmation_code"]', otpCode)
    await page.click('button[type="submit"]')
    // Wait for successful auth
    const appUrl = new URL(process.env.TEST_APP_URL!)
    await expect(page).toHaveURL(
    new RegExp(appUrl.hostname.replaceAll(".", "\\.")),
    )
    await expect(page.locator('[data-testid="user-profile"]')).toBeVisible()
    } finally {
    // Clean up OTP email
    await deleteEmail()
    }
    })
    })

Test passwordless sign-in flow

Link to this section

To test the passwordless sign-in flow:

  1. Enable the Email + code option in Authentication methods.

  2. Sign up for a new test user using the Mailosaur domain (e.g., test-123@your-server-id.mailosaur.net).

  3. Save the test user email to your .env file as TEST_USER_EMAIL.

  4. Create a new test file:

    Terminal window
    touch tests/passwordless-signin.spec.ts
  5. Add the following code:

    tests/passwordless-signin.spec.ts
    import { test, expect } from '@playwright/test'
    import { getOTPFromEmail } from './utils/mailosaur'
    test.describe('Passwordless Authentication Flows', () => {
    test('user can sign in with email and code', async ({ page }) => {
    // This test reuses one inbox on every run, so record the start time and
    // pass it to the helper to avoid reading a code from a previous run.
    const testStart = new Date()
    await page.goto(process.env.TEST_APP_URL!)
    await page.click('[data-testid="sign-in-button"]')
    // Wait for Kinde sign-in page (uses KINDE_ISSUER_URL to support custom domains)
    const authUrl = new URL(process.env.KINDE_ISSUER_URL!)
    await expect(page).toHaveURL(
    new RegExp(authUrl.hostname.replaceAll('.', '\\.'))
    )
    // Fill sign-in form
    await page.fill('input[name="p_email"]', process.env.TEST_USER_EMAIL!)
    await page.click('button[type="submit"]')
    // Wait for OTP email and extract code (only emails received after this test started)
    const { otpCode, deleteEmail } = await getOTPFromEmail(
    process.env.TEST_USER_EMAIL!,
    testStart
    )
    try {
    // Enter OTP
    await page.fill('input[name="p_confirmation_code"]', otpCode)
    await page.click('button[type="submit"]')
    // Wait for successful auth
    const appUrl = new URL(process.env.TEST_APP_URL!)
    await expect(page).toHaveURL(
    new RegExp(appUrl.hostname.replaceAll('.', '\\.'))
    )
    await expect(page.locator('[data-testid="user-profile"]')).toBeVisible()
    } finally {
    // Clean up OTP email
    await deleteEmail()
    }
    })
    })

Test sign-up flow with email and password

Link to this section

Users who sign up through Kinde’s hosted pages verify their email with a one-time code, whichever authentication method they use. This example covers that case for the Email + password method, so the code step appears here too. If your test only needs a signed-up user rather than the sign-up screens, create a pre-verified user through the Management API instead and skip the inbox.

This example uses the Kinde email + password authentication method to sign up a new test user.

  1. Create a new test file:

    Terminal window
    touch tests/email-password-signup.spec.ts
  2. Add the following code:

    tests/email-password-signup.spec.ts
    import { test, expect } from '@playwright/test'
    import { getOTPFromEmail } from './utils/mailosaur'
    const serverId = process.env.MAILOSAUR_SERVER_ID!
    test.describe('Authentication Flows', () => {
    test('user can sign up with email and password', async ({ page }) => {
    // Generate unique email for this test run
    const timestamp = Date.now()
    const testEmail = `test-${timestamp}@${serverId}.mailosaur.net`
    await page.goto(process.env.TEST_APP_URL!)
    await page.click('[data-testid="sign-up-button"]')
    // Wait for Kinde sign-up page (uses KINDE_ISSUER_URL to support custom domains)
    const authUrl = new URL(process.env.KINDE_ISSUER_URL!)
    await expect(page).toHaveURL(
    new RegExp(authUrl.hostname.replaceAll('.', '\\.'))
    )
    // Fill sign-up form
    await page.fill('input[name="p_first_name"]', 'John')
    await page.fill('input[name="p_last_name"]', 'Doe')
    await page.fill('input[name="p_email"]', testEmail)
    // Uncomment the line below if Clickwrap agreements (Terms & Conditions) are enabled in your Kinde environment:
    // await page.check('input[name="p_has_clickwrap_accepted"]')
    await page.click('button[type="submit"]')
    // Wait for OTP email
    const { otpCode, deleteEmail } = await getOTPFromEmail(testEmail)
    try {
    // Enter OTP
    await page.fill('input[name="p_confirmation_code"]', otpCode)
    await page.click('button[type="submit"]')
    // Enter password
    await page.fill(
    'input[name="p_first_password"]',
    process.env.TEST_USER_PASSWORD!
    )
    await page.fill(
    'input[name="p_second_password"]',
    process.env.TEST_USER_PASSWORD!
    )
    await page.click('button[type="submit"]')
    // Wait for successful auth
    const appUrl = new URL(process.env.TEST_APP_URL!)
    await expect(page).toHaveURL(
    new RegExp(appUrl.hostname.replaceAll('.', '\\.'))
    )
    await expect(page.locator('[data-testid="user-profile"]')).toBeVisible()
    } finally {
    // Clean up OTP email
    await deleteEmail()
    }
    })
    })
  1. Use the following command:

    Terminal window
    npx playwright test --ui
  2. Select the test spec to run.

    You should now see the Playwright tests passing in the browser.

    user can sign up with email and code

  3. Go to your Kinde dashboard > Users to find the test users you created.

    Test users in Kinde dashboard

  4. Kinde does not remove these users automatically. Delete them at the end of the test or in a sweep so the addresses can be reused. See Clean up test users.