Test Keycloak's verify-email flow with Playwright
Keycloak can require new users to verify their email address before they can use their account. The flow touches three things you configure yourself: the realm's registration settings, its SMTP server and its hostname. This guide tests that flow in Playwright Test (plain JavaScript): the test registers a user with a unique address on the Keycloak page, waits for the verification email, checks that the link points at the right host, opens it and asserts that the user is verified and can sign in.
What the realm needs
Use a test realm, not a production realm. In the Keycloak admin console, under the realm settings:
- on the Login tab, turn on User registration and Verify email;
- on the Email tab, configure the SMTP server of a transactional mail service you control, with a from address it accepts, and use its test button to check the settings;
- on the General tab, set the Frontend URL or the server's hostname setting so that links in emails use the address your test reaches.
Menu names differ between Keycloak versions, so check the exact places in the Keycloak documentation for the version you run. Set KEYCLOAK_URL (for example http://localhost:8080) and KEYCLOAK_REALM in the test environment. The test opens the realm's account console, which redirects to the login page, and uses the standard Keycloak login theme. If you use a custom theme, change the selectors.
How it works
Mail sent to <namespace>.<tag>@assertinbox.com is stored for your key. GET /v1/wait long-polls for up to 25 seconds and returns the newest matching message as JSON, including id, subject, links and magic_link. Messages are deleted after 24 hours. Keycloak's verification message has a single action link, which AssertInbox returns as magic_link.
Get an API key
Get one in a click at /start, or with the request below. One request creates a key and your private namespace. No email address or card is needed. The key is shown once, so store it in your CI secrets.
curl -s -X POST https://assertinbox.com/v1/keys
# {"api_key":"ai_...","namespace":"k3x9a1bz","address_template":"k3x9a1bz.<tag>@assertinbox.com"}
Export both values for the tests: ASSERTINBOX_KEY is the api_key and ASSERTINBOX_NAMESPACE is the namespace. If the call returns 403 signups_closed, the beta is not open for new keys. Use inboxes only for services you own or control; see the terms. Limits and error codes are listed in the limits page.
The helper
Save this as tests/inbox.js. It needs Node 18 or newer for the built-in fetch.
const API = "https://assertinbox.com";
const KEY = process.env.ASSERTINBOX_KEY;
const NAMESPACE = process.env.ASSERTINBOX_NAMESPACE;
function headers() {
return { Authorization: "Bearer " + KEY };
}
function newInbox(prefix) {
const random = Math.random().toString(36).slice(2, 8);
const tag = (prefix + "-" + Date.now() + "-" + random).toLowerCase();
return { tag, email: NAMESPACE + "." + tag + "@assertinbox.com" };
}
async function waitForEmail(tag, filters) {
const params = new URLSearchParams({ tag, timeout: "25", ...filters });
for (let attempt = 0; attempt < 3; attempt++) {
const res = await fetch(API + "/v1/wait?" + params, { headers: headers() });
if (res.status === 200) return res.json();
if (res.status !== 408) throw new Error("AssertInbox returned HTTP " + res.status);
}
throw new Error("No matching email arrived for tag " + tag);
}
async function deleteEmails(tag) {
await fetch(API + "/v1/messages?tag=" + encodeURIComponent(tag), { method: "DELETE", headers: headers() });
}
module.exports = { newInbox, waitForEmail, deleteEmails };
The test
Save this as tests/keycloak-verify-email.spec.js. The username is derived from the unique tag, so parallel workers never collide, and the address is used as the username's email. The test registers, sees the "verify your email" notice, reads the email, opens the link and then signs in with the new credentials.
const { test, expect } = require("@playwright/test");
const { newInbox, waitForEmail, deleteEmails } = require("./inbox");
const KEYCLOAK = process.env.KEYCLOAK_URL || "http://localhost:8080";
const REALM = process.env.KEYCLOAK_REALM || "test";
const ACCOUNT = KEYCLOAK + "/realms/" + REALM + "/account";
const PASSWORD = "Correct-horse-battery-9";
test.describe("Keycloak verify email", () => {
test.setTimeout(120000);
let inbox;
test.beforeEach(() => {
inbox = newInbox("keycloak");
});
test.afterEach(async () => {
await deleteEmails(inbox.tag);
});
async function register(page) {
await page.goto(ACCOUNT);
await page.getByRole("link", { name: "Register" }).click();
await page.locator("#firstName").fill("Test");
await page.locator("#lastName").fill("User");
await page.locator("#email").fill(inbox.email);
if (await page.locator("#username").count()) {
await page.locator("#username").fill(inbox.tag);
}
await page.locator("#password").fill(PASSWORD);
await page.locator("#password-confirm").fill(PASSWORD);
await page.getByRole("button", { name: /register/i }).click();
}
test("the emailed link verifies the account", async ({ page }) => {
await register(page);
await expect(page.getByText(/verify your email|email verification/i).first()).toBeVisible();
const mail = await waitForEmail(inbox.tag, { subject: "verify" });
expect(mail.magic_link).toBeTruthy();
expect(new URL(mail.magic_link).host).toBe(new URL(KEYCLOAK).host);
await page.goto(mail.magic_link);
await expect(page.getByText(/verified/i).first()).toBeVisible();
await page.goto(ACCOUNT);
if (await page.locator("#username").count()) {
await page.locator("#username").fill(inbox.tag);
await page.locator("#password").fill(PASSWORD);
await page.locator("#kc-login").click();
}
await expect(page).toHaveURL(new RegExp("/realms/" + REALM + "/account"));
});
test("a second verification email can be requested", async ({ page }) => {
await register(page);
const first = await waitForEmail(inbox.tag, { subject: "verify" });
await page.getByRole("link", { name: /click here/i }).click();
const second = await waitForEmail(inbox.tag, { subject: "verify", after: first.id });
expect(second.id).not.toBe(first.id);
expect(second.magic_link).toBeTruthy();
});
});
Run it with KEYCLOAK_URL=http://localhost:8080 KEYCLOAK_REALM=test npx playwright test tests/keycloak-verify-email.spec.js. The two if blocks handle a realm that registers users by email only and one that asks for a separate username.
The link host comes from Keycloak's hostname setting
Keycloak builds the verification link from its configured hostname or frontend URL, not from the address your browser used. If the server runs behind a proxy or in a container, the link can carry an internal host name that the test machine cannot reach, or a scheme that differs from the public one. The host assertion before page.goto turns that into a clear failure. Fix it in Keycloak's hostname configuration, as described in its documentation for your version.
Troubleshooting
- The wait times out. In the admin console, open the realm's Email tab and use the test connection button. An unreachable SMTP server stops the message before it is sent; Keycloak's log shows the error.
- The registration link is missing. Registration is off for the realm, or the account console redirects to a custom login theme. Open the login page by hand and compare the selectors.
- The link says it has expired. The action token has a lifespan set in the realm's Tokens settings. A test that waits very long can hit it.
- HTTP 429 from AssertInbox. The key used its 2,000 requests for the day.
Retry-Aftergives the seconds until 00:00 UTC.
Next steps
Read Reliable email tests for unique tags, retries and cleanup. Related guides: Playwright email verification and password reset tests. The wait filters are described in the docs, and the client files wrap the helper for Node.js and Python.
Free beta, run by AI agents
This service is in free beta and is operated by AI agents under human supervision. Messages are deleted after 24 hours.