Test an AWS Cognito sign-up confirmation code with Node.js
When a Cognito user pool verifies email addresses, a new user receives a six-digit confirmation code and the account stays unconfirmed until the code is submitted. This guide tests that flow with the AWS SDK for JavaScript v3 and Node's built-in test runner. The test signs up with a unique address, waits for the email, confirms the user with the code, and asserts that signing in works afterwards, and that it did not work before. No browser is involved, so it runs in a few seconds.
What the test needs from your pool
Use a dedicated test user pool, never your production pool. It needs:
- email as a sign-in alias or as the username, with email verification by confirmation code;
- an app client without a client secret, with the
ALLOW_USER_PASSWORD_AUTHflow enabled, so thatInitiateAuthCommandcan sign in with a password; - AWS credentials for the test run that are allowed to call
AdminDeleteUseron that pool, which the test uses for cleanup.
Cognito can send email itself or through Amazon SES. Check the email sending limits and the sandbox rules for your setup in AWS's own documentation; a pool that sends many confirmation emails can hit a daily quota, and the test will then time out while waiting. Set COGNITO_REGION, COGNITO_POOL_ID and COGNITO_CLIENT_ID in the environment. Install the SDK with npm install @aws-sdk/client-cognito-identity-provider.
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, otp and links. The otp field holds the code already extracted from the message. 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. Limits and error codes are listed in the limits page.
The helper
Save this as test/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 test/cognito-signup.test.js and run it with node --test. It signs up, proves that an unconfirmed user cannot sign in, confirms with the emailed code and signs in. The after hook deletes the test user and the messages.
const test = require("node:test");
const assert = require("node:assert");
const {
CognitoIdentityProviderClient,
SignUpCommand,
ConfirmSignUpCommand,
InitiateAuthCommand,
AdminDeleteUserCommand,
} = require("@aws-sdk/client-cognito-identity-provider");
const { newInbox, waitForEmail, deleteEmails } = require("./inbox");
const client = new CognitoIdentityProviderClient({ region: process.env.COGNITO_REGION });
const CLIENT_ID = process.env.COGNITO_CLIENT_ID;
const POOL_ID = process.env.COGNITO_POOL_ID;
const PASSWORD = "Correct-horse-battery-9";
function signIn(email, password) {
return client.send(
new InitiateAuthCommand({
AuthFlow: "USER_PASSWORD_AUTH",
ClientId: CLIENT_ID,
AuthParameters: { USERNAME: email, PASSWORD: password },
})
);
}
test("sign-up confirmation code confirms the user", { timeout: 120000 }, async (t) => {
const inbox = newInbox("cognito");
t.after(async () => {
await deleteEmails(inbox.tag);
await client.send(new AdminDeleteUserCommand({ UserPoolId: POOL_ID, Username: inbox.email })).catch(() => {});
});
const signUp = await client.send(
new SignUpCommand({
ClientId: CLIENT_ID,
Username: inbox.email,
Password: PASSWORD,
UserAttributes: [{ Name: "email", Value: inbox.email }],
})
);
assert.strictEqual(signUp.UserConfirmed, false);
await assert.rejects(() => signIn(inbox.email, PASSWORD), { name: "UserNotConfirmedException" });
const mail = await waitForEmail(inbox.tag, { subject: "verification code" });
assert.match(mail.otp, /^[0-9]{6}$/);
await assert.rejects(
() => client.send(new ConfirmSignUpCommand({ ClientId: CLIENT_ID, Username: inbox.email, ConfirmationCode: "000000" })),
{ name: "CodeMismatchException" }
);
await client.send(new ConfirmSignUpCommand({ ClientId: CLIENT_ID, Username: inbox.email, ConfirmationCode: mail.otp }));
const session = await signIn(inbox.email, PASSWORD);
assert.ok(session.AuthenticationResult.AccessToken);
});
The wrong-code check uses 000000. A real code could in theory be 000000 too; the chance is one in a million, and if you want the test to be strictly deterministic, pick a wrong code that differs from mail.otp.
Why each assertion is there
UserConfirmedis false. The pool did not auto-confirm the user, which would make the email step meaningless.- Sign-in is refused before confirmation. It proves that the code, not the sign-up call, changes the state.
- The code has six digits. A template change that moves the code into an image or a link would fail here first.
- A wrong code is rejected. Cognito answers with
CodeMismatchException, which your own UI should translate into a helpful message.
Troubleshooting
- The wait times out. Look at the email configuration of the pool and at your account's email sending quota in the AWS console. The default subject of the confirmation message contains "verification code"; if you customised it, change the filter.
InvalidParameterExceptionon sign-up. The pool's username settings do not allow an email address as the username, or the password policy rejects the test password.NotAuthorizedExceptionon sign-in. The app client does not allowUSER_PASSWORD_AUTH.- 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: Supabase Auth and API-only tests in Node.js. 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.