Skip to content
  • Testing

Setup test user and environment

Before you begin testing your application with Kinde authentication, you need to set up dedicated test users and configure your test environment. This setup is common across all testing methods, whether you’re testing backend APIs, authentication flows, or authenticated features.

  • A Kinde account with admin access (Sign up for free)

Why separate test users and environments?

Link to this section

Using dedicated test infrastructure for automated testing provides several benefits:

  • Data isolation: Test data doesn’t mix with production user data
  • Reliability: Tests won’t be affected by real user activity
  • Security: Test credentials are separate from production credentials
  • Compliance: Easier to manage test data retention and privacy requirements
  • Stability: Test users can be configured with specific permissions and settings

Step 1: Create a test environment

Link to this section

Kinde allows creating multiple non-production environments. This is useful for testing in different environments without having to sign up for a new account.

  1. Sign in to your Kinde dashboard and select the Production dropdown. A pop-up appears.
    • Select All environments
    setup test environment in kinde
  2. Select Add environment. A pop-up appears.
  3. Enter the environment name and code (e.g., “Test”)
  4. Select Save

You are now in the test environment.

Step 2: Create a test user

Link to this section

You can create test users in two ways. Pick the one that fits how your suite runs:

  • Option A: Add a user in the Kinde dashboard. Best for one or two long-lived users that your whole suite shares. You sign in once by hand to verify the email and set a password.
  • Option B: Create a pre-verified user with the Management API. Best when your tests create and delete their own users, or when nobody can click through a verification code (for example in CI). The user is created with the email already verified and a password already set, so no inbox is involved.

Both options give you a test user who signs in with Email + password.

Option A: Add a user in the Kinde dashboard

Link to this section
  1. Go to the Users tab and select Add user
  2. Enter test user details:
    • First name and Last name: (e.g., “John Doe”)
    • Email: Use a clear test email (e.g., e2e-test@yourcompany.com)
  3. Select Save

Repeat this process for each test user you need to create. Finish the account in Step 4.

Option B: Create a pre-verified test user with the Management API

Link to this section

The Management API lets you create a user whose email identity is already marked as verified, then set a password on it. Kinde treats a verified identity the same way whether it was verified by a one-time code or by the API, so the user signs in with email and password straight away and is never asked for a code.

  • A machine-to-machine (M2M) application in your test environment authorized for the Kinde Management API, with these scopes: create:users, update:user_passwords, read:users, delete:users. See Call the Kinde Management API for how to create one and get a token.

  • The M2M client ID and secret in your .env file, alongside the values from the Playwright setup:

    # ... other environment variables ...
    KINDE_DOMAIN=https://your-subdomain.kinde.com
    KINDE_MANAGEMENT_CLIENT_ID=your-m2m-client-id
    KINDE_MANAGEMENT_CLIENT_SECRET=your-m2m-client-secret

The three calls

Link to this section
  1. Create the user with a verified email identity. POST /api/v1/user (scope create:users). Set is_verified to true on the email identity. Pass organization_code if your application is B2B or the environment does not add new users to a default organization.

    Terminal window
    curl --request POST \
    --url "$KINDE_DOMAIN/api/v1/user" \
    --header "Authorization: Bearer $KINDE_MANAGEMENT_TOKEN" \
    --header "Content-Type: application/json" \
    --data '{
    "profile": { "given_name": "E2E", "family_name": "Test" },
    "identities": [
    {
    "type": "email",
    "is_verified": true,
    "details": { "email": "e2e-tmp-1730000000@yourcompany.com" }
    }
    ]
    }'

    The response includes the new user’s id (for example kp_c3143a4b50ad43c88e541d9077681782). Keep it: you need it for the next call and for cleanup.

  2. Set a password. PUT /api/v1/users/{user_id}/password (scope update:user_passwords). The endpoint accepts a hash, not the plain-text password, so hash it first. The default hashing_method is bcrypt. Leave is_temporary_password unset so the user is not asked to change it on first sign-in.

    Terminal window
    curl --request PUT \
    --url "$KINDE_DOMAIN/api/v1/users/$USER_ID/password" \
    --header "Authorization: Bearer $KINDE_MANAGEMENT_TOKEN" \
    --header "Content-Type: application/json" \
    --data '{
    "hashed_password": "$2a$10$t8Jz3hJCCTFk/Acja7bw3OpamB3xuLPhpJlRHb31bXIjfzeTfn8rq",
    "hashing_method": "bcrypt"
    }'

    The first time the user signs in, Kinde checks the password against the hash you supplied and then stores it in its own format. Nothing else changes for the user.

  3. Sign in. The user can now sign in on Kinde’s hosted pages with their email and the password you hashed, with no verification code. Store the email and password for your tests.

A reusable helper for Playwright

Link to this section

The helper below wraps the calls above so a test can ask for a fresh user in one line. It uses bcryptjs to hash the password locally.

  1. Install the dependency:

    Terminal window
    npm i -D bcryptjs @types/bcryptjs
  2. Create tests/utils/kinde-users.ts:

    tests/utils/kinde-users.ts
    import bcrypt from "bcryptjs"
    import fs from "node:fs"
    import path from "node:path"
    import "dotenv/config"
    const domain = process.env.KINDE_DOMAIN!
    const signedUpEmailsFile = path.join(process.cwd(), "tests/.e2e-signed-up-emails.json")
    export type TestUser = { id: string; email: string; password: string }
    let cachedToken: { value: string; expiresAt: number } | undefined
    async function managementToken(): Promise<string> {
    if (cachedToken && cachedToken.expiresAt > Date.now() + 60_000) {
    return cachedToken.value
    }
    const res = await fetch(`${domain}/oauth2/token`, {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body: new URLSearchParams({
    grant_type: "client_credentials",
    client_id: process.env.KINDE_MANAGEMENT_CLIENT_ID!,
    client_secret: process.env.KINDE_MANAGEMENT_CLIENT_SECRET!,
    audience: `${domain}/api`,
    }),
    })
    if (!res.ok) throw new Error(`Token request failed: ${res.status}`)
    const json = (await res.json()) as { access_token: string; expires_in: number }
    cachedToken = { value: json.access_token, expiresAt: Date.now() + json.expires_in * 1000 }
    return cachedToken.value
    }
    async function api(path: string, init: RequestInit = {}) {
    const res = await fetch(`${domain}/api/v1${path}`, {
    ...init,
    headers: {
    Authorization: `Bearer ${await managementToken()}`,
    "Content-Type": "application/json",
    ...(init.headers ?? {}),
    },
    })
    if (!res.ok) {
    throw new Error(`${init.method ?? "GET"} ${path} failed: ${res.status} ${await res.text()}`)
    }
    return res.json()
    }
    /**
    * Creates a user with a verified email identity and a known password.
    * Pass organizationCode for B2B applications.
    */
    export async function createTestUser(options: { organizationCode?: string } = {}): Promise<TestUser> {
    const email = `e2e-tmp-${Date.now()}-${Math.random().toString(36).slice(2, 8)}@yourcompany.com`
    const password = `Pw!${Math.random().toString(36).slice(2)}${Date.now()}`
    const created = await api("/user", {
    method: "POST",
    body: JSON.stringify({
    profile: { given_name: "E2E", family_name: "Test" },
    organization_code: options.organizationCode,
    identities: [{ type: "email", is_verified: true, details: { email } }],
    }),
    })
    try {
    await api(`/users/${created.id}/password`, {
    method: "PUT",
    body: JSON.stringify({
    hashed_password: await bcrypt.hash(password, 10),
    hashing_method: "bcrypt",
    }),
    })
    } catch (error) {
    await deleteTestUser(created.id).catch((cleanupError) => {
    console.error(`Failed to delete test user ${created.id}`, cleanupError)
    })
    throw error
    }
    return { id: created.id, email, password }
    }
    /** Deletes the user and their profile so the email can be reused. */
    export async function deleteTestUser(id: string): Promise<void> {
    await api(`/user?id=${encodeURIComponent(id)}&is_delete_profile=true`, { method: "DELETE" })
    }
    /** Finds users by exact email. Use for addresses recorded during the run. */
    export async function findUsersByEmail(...emails: string[]): Promise<Array<{ id: string; email: string }>> {
    const query = encodeURIComponent(emails.join(","))
    const users: Array<{ id: string; email: string }> = []
    let nextToken: string | undefined
    do {
    const token = nextToken ? `&next_token=${encodeURIComponent(nextToken)}` : ""
    const json = await api(`/users?email=${query}&page_size=100${token}`)
    users.push(...(json.users ?? []))
    nextToken = json.next_token
    } while (nextToken)
    return users
    }
    /**
    * Lists users whose email starts with a prefix and who were created before
    * `olderThanMs` ago. `GET /api/v1/users?email=` is exact match only, so the
    * prefix is applied here. The age check leaves a parallel CI run's users alone.
    */
    export async function findUsersByEmailPrefix(
    prefix: string,
    olderThanMs: number,
    ): Promise<Array<{ id: string; email: string }>> {
    const cutoff = Date.now() - olderThanMs
    const users: Array<{ id: string; email: string }> = []
    let nextToken: string | undefined
    do {
    const token = nextToken ? `&next_token=${encodeURIComponent(nextToken)}` : ""
    const json = await api(`/users?page_size=100${token}`)
    for (const user of json.users ?? []) {
    if (!user.email?.startsWith(prefix) || !user.created_on) continue
    if (Date.parse(user.created_on) > cutoff) continue
    users.push(user)
    }
    nextToken = json.next_token
    } while (nextToken)
    return users
    }
    /** Call after a test signs up through hosted pages so globalTeardown can delete the user. */
    export function recordSignedUpEmail(email: string): void {
    const emails: string[] = fs.existsSync(signedUpEmailsFile)
    ? JSON.parse(fs.readFileSync(signedUpEmailsFile, "utf8"))
    : []
    emails.push(email)
    fs.mkdirSync(path.dirname(signedUpEmailsFile), { recursive: true })
    fs.writeFileSync(signedUpEmailsFile, JSON.stringify(emails))
    }

    Replace yourcompany.com with a domain you control. The address never receives mail, so it only has to be unique.

  3. Expose the user as a Playwright fixture so every test gets its own and cleanup happens even when the test fails. Create tests/fixtures.ts:

    tests/fixtures.ts
    import { test as base } from "@playwright/test"
    import { createTestUser, deleteTestUser, type TestUser } from "./utils/kinde-users"
    export const test = base.extend<{ testUser: TestUser }>({
    testUser: async ({}, use) => {
    const user = await createTestUser()
    try {
    await use(user)
    } finally {
    await deleteTestUser(user.id)
    }
    },
    })
    export { expect } from "@playwright/test"
  4. Use it in a test. This signs in a brand-new user with no inbox involved:

    tests/fresh-user-signin.spec.ts
    import { test, expect } from "./fixtures"
    test("a freshly created user can sign in with email and password", async ({ page, testUser }) => {
    await page.goto(process.env.TEST_APP_URL!)
    await page.click('[data-testid="sign-in-button"]')
    const authUrl = new URL(process.env.KINDE_ISSUER_URL!)
    await expect(page).toHaveURL(new RegExp(authUrl.hostname.replaceAll(".", "\\.")))
    await page.fill('input[name="p_email"]', testUser.email)
    await page.click('button[type="submit"]')
    await page.fill('input[name="p_password"]', testUser.password)
    await page.click('button[type="submit"]')
    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()
    })

If you already use the @kinde/management-api-js SDK, the same four calls are available as Users.createUser, Users.setUserPassword, Users.getUsers and Users.deleteUser.

Step 3: Create test application credentials

Link to this section

You will need the client ID, client secret, and access token when running certain tests.

  1. Go to your Kinde dashboard and select Add application

  2. Enter a name for the application (e.g., “Test Application”)

  3. Select the application type (e.g., “Back-end web”)

  4. Select Save

  5. On the Quick start page, select a technology (e.g., “Next.js”) and select Save

  6. Configure the callback URLs

  7. Go to Authentication:

    1. Uncheck Email + code
    2. Check Email + password email password authentication in kinde
  8. Select Save

    Optional: Go to Tokens to configure a custom token expiration time for this application.

Step 4: Finish test user account creation (Option A only)

Link to this section

If you created the test user in the dashboard, finish the account by signing in once:

  1. Set up and run your test application
  2. Sign in with the test user you created
  3. Verify the email address and set up a strong password
  4. Store the test user email and password for use in your tests

Users created with the Management API (Option B) are already verified and already have a password, so skip this step.

Kinde starter test application

Link to this section

If you are creating your tests from scratch, you can use the Kinde Next.js end-to-end test application to get started.

Clean up test users

Link to this section

Kinde does not expire or delete test users automatically. Every user your suite creates stays in the environment until something removes it, so build cleanup into the suite rather than leaving it to the dashboard.

  • Per test: create the user in setup and delete it in teardown. The testUser fixture in Option B does this, and runs the delete even when the test fails.
  • Users your tests sign up through the hosted pages (for example the passwordless sign-up tests) are not created by the fixture, so delete them yourself at the end of the test or in a sweep.
  • Sweep leftovers on a schedule or at the end of a CI run: delete users you recorded during the run (exact emails), and separately page through GET /api/v1/users for Option B leftovers. Use a prefix that shared dashboard users do not share (for example e2e-tmp-), and only delete matches whose created_on is older than about an hour so a parallel CI run still using its users is left alone. GET /api/v1/users?email= matches exact addresses only. Use is_delete_profile=true so the profile is removed and the address can be reused.

The relevant calls are GET /api/v1/users?email=<comma-separated emails> (exact match, scope read:users) and DELETE /api/v1/user?id=<user id>&is_delete_profile=true (scope delete:users). A small sweep using the helper above deletes users one at a time so you stay within the Management API concurrency limits. If you need to remove many users at once and see 429 responses, add retries with exponential backoff as described in that guide.

tests/global-teardown.ts
import fs from "node:fs"
import path from "node:path"
import { deleteTestUser, findUsersByEmail, findUsersByEmailPrefix } from "./utils/kinde-users"
const signedUpEmailsFile = path.join(process.cwd(), "tests/.e2e-signed-up-emails.json")
export default async function globalTeardown() {
const emails: string[] = fs.existsSync(signedUpEmailsFile)
? JSON.parse(fs.readFileSync(signedUpEmailsFile, "utf8"))
: []
const recorded = emails.length > 0 ? await findUsersByEmail(...emails) : []
// Option B emails start with e2e-tmp-, which the shared dashboard user does not.
// Skip anyone created in the last hour so another CI run is not swept mid-flight.
const orphans = await findUsersByEmailPrefix("e2e-tmp-", 60 * 60 * 1000)
const ids = new Set([...recorded, ...orphans].map((u) => u.id))
for (const id of ids) {
await deleteTestUser(id)
}
if (fs.existsSync(signedUpEmailsFile)) fs.unlinkSync(signedUpEmailsFile)
}

In passwordless sign-up tests, call recordSignedUpEmail(testEmail) from ./utils/kinde-users after the user completes sign-up. Add tests/.e2e-signed-up-emails.json to .gitignore.

Register it in playwright.config.ts with globalTeardown: "./tests/global-teardown.ts".

Best practices

Link to this section
  • Document test resources: Keep track of test users, applications, and their purposes
  • Regular maintenance: Rotate test credentials periodically and clean up test users your suite creates
  • Clear naming: Use a prefix for disposable Management API users that shared dashboard users do not share, such as e2e-tmp-. Page through users and delete only matches older than about an hour. GET /api/v1/users?email= does not support prefix search.
  • Scope the M2M application tightly: Give the test M2M application only the user scopes it needs, and keep it in the test environment

After completing the above steps, you now have:

  • A test environment
  • A test user with email and password, or a fixture that creates and deletes one per test
  • A test application

You can now start testing your application with Kinde authentication.