Cypress OTP login: reading the code from email
Passwordless login sends a six-digit code to the user's email. A Cypress test cannot open an inbox, but it can call an HTTP API. This guide builds a custom command, cy.getEmail(tag), that waits for a message sent to a unique test address and returns it with the code already extracted. It uses plain JavaScript and cy.request, with no plugins.
How it works
Any address shaped like <namespace>.<tag>@assertinbox.com is a private inbox for your key. GET /v1/wait?tag=... holds the request open for up to 25 seconds and returns the newest message with otp and links, or 408 timeout if nothing arrived. Messages are deleted after 24 hours.
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.
Configuration
Pass the key and namespace to Cypress as environment variables. Cypress reads any variable that starts with CYPRESS_, so set CYPRESS_ASSERTINBOX_KEY and CYPRESS_ASSERTINBOX_NAMESPACE in your shell or CI secrets. The config only needs a base URL for your app:
const { defineConfig } = require("cypress");
module.exports = defineConfig({
e2e: {
baseUrl: process.env.APP_URL || "http://localhost:3000",
defaultCommandTimeout: 10000,
requestTimeout: 35000,
},
});
requestTimeout must be larger than the 25-second wait, otherwise Cypress aborts the request first.
The custom command
Put this in cypress/support/commands.js. It retries after a 408, which is the normal result when the email is slow, and fails on any other status.
const API = "https://assertinbox.com";
Cypress.Commands.add("newInbox", () => {
const random = Math.random().toString(36).slice(2, 8);
const tag = ("cy-" + Date.now() + "-" + random).toLowerCase();
const email = Cypress.env("ASSERTINBOX_NAMESPACE") + "." + tag + "@assertinbox.com";
return cy.wrap({ tag, email }, { log: false });
});
Cypress.Commands.add("getEmail", (tag, attempts = 3) => {
return cy
.request({
url: API + "/v1/wait?tag=" + encodeURIComponent(tag) + "&timeout=25",
headers: { Authorization: "Bearer " + Cypress.env("ASSERTINBOX_KEY") },
failOnStatusCode: false,
timeout: 35000,
log: false,
})
.then((res) => {
if (res.status === 200) return res.body;
if (res.status === 408 && attempts > 1) return cy.getEmail(tag, attempts - 1);
throw new Error("No email for tag " + tag + " (HTTP " + res.status + ")");
});
});
Cypress.Commands.add("clearEmails", (tag) => {
return cy.request({
method: "DELETE",
url: API + "/v1/messages?tag=" + encodeURIComponent(tag),
headers: { Authorization: "Bearer " + Cypress.env("ASSERTINBOX_KEY") },
log: false,
});
});
Make sure cypress/support/e2e.js loads the file with require("./commands"). Cypress loads that support file before every spec.
The test
describe("passwordless login", () => {
it("logs in with the emailed code", () => {
cy.newInbox().then((inbox) => {
cy.visit("/login");
cy.get("input[name=email]").type(inbox.email);
cy.contains("button", "Send code").click();
cy.getEmail(inbox.tag).then((mail) => {
expect(mail.otp, "otp").to.match(/^[0-9]{4,8}$/);
cy.get("input[name=code]").type(mail.otp);
cy.contains("button", "Log in").click();
cy.contains("Welcome");
cy.clearEmails(inbox.tag);
});
});
});
});
Handling the 408 retry
A 408 is not an error in the API, it just means "nothing yet". The command retries up to three times, so a slow mail queue gets about 75 seconds in total. Raise attempts for a slower system, but keep an eye on the budget: every wait costs one request against your 2,000 per UTC day, and GET /v1/me shows how many you have used.
When the app sends a second email
A "Resend code" button sends another message to the same address. /v1/wait returns the newest message for the tag, which at that moment may still be the first one, so a test that waits again can type an old code. Pass the id of the message you already read as after, and the call returns only a newer message. Add this command next to the others in cypress/support/commands.js:
Cypress.Commands.add("getNewEmail", (tag, afterId) => {
return cy
.request({
url: API + "/v1/wait?tag=" + encodeURIComponent(tag) + "&timeout=25&after=" + encodeURIComponent(afterId),
headers: { Authorization: "Bearer " + Cypress.env("ASSERTINBOX_KEY") },
failOnStatusCode: false,
timeout: 35000,
log: false,
})
.then((res) => {
if (res.status === 200) return res.body;
throw new Error("No newer email for tag " + tag + " (HTTP " + res.status + ")");
});
});
Then the test reads the first email, clicks resend, and waits for a message that arrived after it:
describe("resend code", () => {
it("sends a different code after Resend", () => {
cy.newInbox().then((inbox) => {
cy.visit("/login");
cy.get("input[name=email]").type(inbox.email);
cy.contains("button", "Send code").click();
cy.getEmail(inbox.tag).then((first) => {
cy.contains("button", "Resend").click();
cy.getNewEmail(inbox.tag, first.id).then((second) => {
expect(second.id).to.not.equal(first.id);
cy.get("input[name=code]").type(second.otp);
cy.contains("button", "Log in").click();
cy.contains("Welcome");
});
});
});
});
});
The from and subject filters combine with after when your app sends several kinds of email to one address. A plain since value, in Unix seconds, also works when you do not have a message id.
Client files instead of a helper
If you would rather not keep your own helper, the client files for JavaScript and Python do the same job: they build addresses, wait with retries on 408, and accept the from, subject and after filters. They are single files you download with curl. The daily allowance, the retention period and every error code are listed on the limits page.
Troubleshooting
- The request fails immediately with 401. The key is missing in the Cypress environment. Print
Cypress.env("ASSERTINBOX_KEY") !== undefined, never the key itself. - The test passes locally but times out in CI. Check that CI sends real mail. Many staging setups use a mail catcher that never leaves the network.
- Retries re-use an old code. Each attempt creates a new inbox through
newInbox, so an old message cannot match. If you reuse a tag deliberately, passsince(a Unix time in seconds) to/v1/wait. otpis null. The email has no labelled code. Readmail.textand extract it yourself; see the docs for the rules.
Related guides: Playwright email verification, pytest with Playwright for Python.