Setup Cypress
Testing
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.
Using dedicated test infrastructure for automated testing provides several benefits:
Kinde allows creating multiple non-production environments. This is useful for testing in different environments without having to sign up for a new account.
You are now in the test environment.
You can create test users in two ways. Pick the one that fits how your suite runs:
Both options give you a test user who signs in with Email + password.
e2e-test@yourcompany.com)Repeat this process for each test user you need to create. Finish the account in Step 4.
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 verified identity only removes the verification step for Email + password sign-in. With Email + code (passwordless), the code is the credential, so Kinde always sends one. Use this option to keep the inbox out of every test except the ones that test the passwordless screens themselves. For those, see Test passwordless flows.
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.comKINDE_MANAGEMENT_CLIENT_ID=your-m2m-client-idKINDE_MANAGEMENT_CLIENT_SECRET=your-m2m-client-secretThe M2M secret grants write access to the users in your environment. Keep it in your CI secret store and never commit it. Use an M2M application in your test environment, not production.
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.
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.
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.
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.
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.
Skipping the verification code does not skip other screens after sign-in. If the test environment requires MFA, prompts to set up a passkey, or asks the user to accept terms, the user still lands on those screens and a test that only fills email and password fails. Turn those off in the test environment, or handle them in the test.
The Block disposable email addresses policy applies to sign-ups through Kinde’s hosted pages. It is not applied to users created with the Management API, so you can create API test users on a Mailosaur or similar domain even while the policy is on.
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.
Install the dependency:
npm i -D bcryptjs @types/bcryptjspnpm add -D bcryptjs @types/bcryptjsyarn add -D bcryptjs @types/bcryptjsbun add -d bcryptjs @types/bcryptjsCreate 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.
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:
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"Use it in a test. This signs in a brand-new user with no inbox involved:
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.
You will need the client ID, client secret, and access token when running certain tests.
Go to your Kinde dashboard and select Add application
Enter a name for the application (e.g., “Test Application”)
Select the application type (e.g., “Back-end web”)
Select Save
On the Quick start page, select a technology (e.g., “Next.js”) and select Save
Configure the callback URLs
Go to Authentication:
Select Save
Optional: Go to Tokens to configure a custom token expiration time for this application.
If you created the test user in the dashboard, finish the account by signing in once:
Users created with the Management API (Option B) are already verified and already have a password, so skip this step.
If you are creating your tests from scratch, you can use the Kinde Next.js end-to-end test application to get started.
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.
testUser fixture in Option B does this, and runs the delete even when the test fails.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.
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".
Deleting a user ends their sessions and invalidates their refresh tokens. Access tokens already issued stay valid until they expire, so a service that validates them locally keeps accepting them. If a test still needs the browser session after teardown, delete the user after the last assertion, not before.
e2e-tmp-. Page through users and delete only matches older than about an hour. GET /api/v1/users?email= does not support prefix search.After completing the above steps, you now have:
You can now start testing your application with Kinde authentication.