Email management
On this page
This guide covers the withManagedEmail mixin from @adonisplus/persona/email. You will learn how to:
- Apply the mixin and understand the two-column email pattern
- Create users with unverified email addresses
- Verify emails using cryptographic tokens
- Handle email change requests safely
- Throttle token creation to prevent abuse
Overview
Section titled "Overview"Your application must verify that a user owns the email address they signed up with. It must also let users change their email later without losing access to their account.
The withManagedEmail mixin uses a two-column email pattern. Your users table stores two values: a verified email (the primary address) and an unverified_email (an address awaiting verification). The two values tell the state of the account.
- When
emailequalsunverified_email, the account is inactive. The user signed up but has not verified their address yet. - When
unverified_emailisnull, the account is active. The primary email is verified and there is no pending change. - When
unverified_emaildiffers fromemail, the user has requested an email change. The primary address stays intact until the new one is verified.
The withManagedEmail mixin needs database tables for storing the pending email and verification tokens, and must be applied to your User model.
Add the unverified email column to users
Section titled "Add the unverified email column to users"Generate a migration to add an
unverified_emailcolumn to your existinguserstable. This column stores a pending email address awaiting verification.node ace make:migration add_unverified_email_to_users --alter=usersimport { BaseSchema } from '@adonisjs/lucid/schema' export default class extends BaseSchema { protected tableName = 'users' async up() { if (await this.schema.hasColumn(this.tableName, 'unverified_email')) { return } this.schema.alterTable(this.tableName, (table) => { table.string('unverified_email', 254).nullable().after('email').index() }) } async down() { this.schema.alterTable(this.tableName, (table) => { table.dropColumn('unverified_email') }) } }Create the email verification tokens table
Section titled "Create the email verification tokens table"Generate a migration for the
email_verification_tokenstable. This table stores hashed verification tokens, each tied to a user and an email address.node ace make:migration create_email_verification_tokensimport hash from '@adonisjs/core/services/hash' import { BaseSchema } from '@adonisjs/lucid/schema' export default class extends BaseSchema { protected tableName = 'email_verification_tokens' async up() { this.schema.createTable(this.tableName, (table) => { table.increments('id') table.integer('tokenable_id').notNullable().unsigned() table.string('email').notNullable() table.string('hash', 80).notNullable() table.timestamp('created_at', { precision: 6, useTz: true }).notNullable() table.timestamp('expires_at', { precision: 6, useTz: true }).nullable() }) } async down() { this.schema.dropTable(this.tableName) } }Apply the mixin
Section titled "Apply the mixin"Apply the
withManagedEmailmixin to your User model usingcompose.import { UserSchema } from '#database/schema' import { compose } from '@adonisjs/core/helpers' import { withManagedEmail } from '@adonisplus/persona/email' export default class User extends compose( UserSchema, withManagedEmail() ) {}You can customize the token provider by passing a config object.
import { UserSchema } from '#database/schema' import { compose } from '@adonisjs/core/helpers' import { withManagedEmail } from '@adonisplus/persona/email' export default class User extends compose( UserSchema, withManagedEmail({ table: 'custom_email_tokens', expiresIn: '2 hours', }) ) {}tablestringThe database table used to store email verification tokens.
Defaults to
"email_verification_tokens".tokenSecretLengthnumberThe length of the cryptographically secure random string used as the token secret.
Defaults to
40.expiresInstring | numberHow long tokens remain valid. Accepts a number in seconds or a time expression string like
'1 day'or'2 hours'.Defaults to
'1 day'.
Creating users
Section titled "Creating users"When you create a new user, set both email and unverifiedEmail to the same value. This marks the account as inactive until the email is verified.
Warning
You must normalize email addresses to lowercase before passing them to the model. The module stores and compares emails exactly as given. If one user signs up with Alice@example.com and another with alice@example.com, a case-sensitive collation (the PostgreSQL default) stores them as two different addresses.
Per RFC 5321, the local part of an email address is technically case-sensitive. In practice, no major email provider enforces this. Lowercasing on input is the industry standard.
import User from '#models/user'
import db from '@adonisjs/lucid/services/db'
import type { HttpContext } from '@adonisjs/core/http'
import { signupValidator } from '#validators/user'
export default class SignupController {
async store({ request, response }: HttpContext) {
const { email, password } = await request.validateUsing(signupValidator)
const token = await db.transaction(async (trx) => {
const user = await User.create({ email, unverifiedEmail: email, password }, { client: trx })
return user.createEmailVerificationToken()
})
// Send token.value!.release() to the user via email
return response.redirect('/login')
}
}
user.hasInactiveAccount is true while email equals unverifiedEmail, and user.hasActiveAccount is its opposite.
Warning
An unverified signup keeps its address in the unique users.email column. Nobody else can sign up with that address until you delete the account. Delete accounts that have stayed inactive (hasInactiveAccount) for a set time, for example from a scheduled command.
Verifying emails
Section titled "Verifying emails"When the user clicks the verification link, pass the token string to the static verifyEmail method. This method verifies the token, checks that no other user already owns the email, and switches the user's email inside a database transaction.
import type { HttpContext } from '@adonisjs/core/http'
export default class EmailVerificationNotificationsController {
async store({ auth, response }: HttpContext) {
const token = await auth.getUserOrFail().createEmailVerificationToken(true, '1 min')
if (token) {
// Send token.value!.release() to the user via email
}
return response.redirect().back()
}
}
If verification fails (invalid token, expired token, email already taken, or user not found), the method throws E_INVALID_EMAIL_TOKEN with status 400. The message is the same for every cause, to prevent information leakage. Pass the redirectTo option to choose where an HTML request is redirected, as the controller above does. See Errors for the response of each request type.
verifyEmail does not delete the token. Call clearEmailVerificationTokens after a successful verification, and before issuing a new token.
Handling email changes
Section titled "Handling email changes"When an existing user changes their email, the request has one of three outcomes.
- The new email is the current one. Nothing changes (
SKIPPED). - The user changed back to their verified email. Clear the pending change and delete all tokens (
REVERTED). - The email is new. Update the pending email, delete the old tokens, and issue a new verification token (
ISSUED_TOKEN).
The withEmail method knows the account state. For an inactive account, it sets both email and unverifiedEmail. For an active account, it sets only unverifiedEmail, which keeps the verified address until the new one is verified. Run the update inside lockForUpdate. The lock prevents two requests from changing the email at the same time.
import type { HttpContext } from '@adonisjs/core/http'
import { changeEmailValidator } from '#validators/user'
export default class AccountEmailController {
async update({ auth, request, response }: HttpContext) {
const { email: newEmail } = await request.validateUsing(changeEmailValidator)
const result = await auth.getUserOrFail().lockForUpdate(async (freshUser) => {
if (!freshUser.hasEmailChanged(newEmail)) {
return { type: 'SKIPPED' } as const
}
if (freshUser.hasEmailReverted(newEmail)) {
freshUser.unverifiedEmail = null
await freshUser.save()
await freshUser.clearEmailVerificationTokens()
return { type: 'REVERTED' } as const
}
await freshUser.withEmail(newEmail).save()
await freshUser.clearEmailVerificationTokens()
return { type: 'ISSUED_TOKEN', token: await freshUser.createEmailVerificationToken() } as const
})
if (result.type === 'ISSUED_TOKEN') {
// Send result.token.value!.release() to the new address via email
}
return response.redirect().back()
}
}
Resending verification emails
Section titled "Resending verification emails"When resending verification emails, use the shouldThrottle parameter to prevent abuse. The first argument enables throttling. The second sets the throttle window (defaults to 60 seconds). When a token was created within the window, the method returns null instead of creating a new one.
// Returns null if a token was created within the throttle window
const resentToken = await user.createEmailVerificationToken(true, '1 min')
if (resentToken) {
// Send resentToken.value!.release() to the user via email
}You should always enable throttling on user-facing endpoints. Without it, every call creates a new token, which lets a single user flood the tokens table.
Errors
Section titled "Errors"verifyEmail throws E_INVALID_EMAIL_TOKEN with status 400. See Errors for the response of each request type.
Instance properties and methods
Section titled "Instance properties and methods"The withManagedEmail mixin adds the following to model instances.
emailstringemail database column.unverifiedEmailstring | nullunverified_email database column. null when there is no pending change.hasActiveAccountbooleantrue when the primary email is verified (unverifiedEmail is null or differs from email).hasInactiveAccountbooleantrue when the primary email has not been verified (email equals unverifiedEmail).createEmailVerificationTokenmethodCreates a verification token for the user's unverifiedEmail. Throws a RuntimeException if unverifiedEmail is null.
// Without throttling
const token = await user.createEmailVerificationToken()
// With throttling (returns null within the window)
const throttledToken = await user.createEmailVerificationToken(true, '1 min')clearEmailVerificationTokensmethodDeletes all email verification tokens for the user. Returns the number of deleted rows.
await user.clearEmailVerificationTokens()hasEmailChangedmethodReturns true if the provided email differs from the current pending email (or the primary email when no pending change exists).
user.hasEmailChanged('new@example.com')hasEmailRevertedmethodReturns true if the user is reverting back to their verified primary email. Only true when unverifiedEmail exists and the new email matches email.
user.hasEmailReverted('original@example.com')withEmailmethodUpdates the local email and unverifiedEmail attributes. For inactive accounts, updates both columns. For active accounts, only updates unverifiedEmail. Returns this for chaining.
await user.withEmail('new@example.com').save()switchEmailmethodSets the primary email and clears unverifiedEmail to null. Used internally by verifyEmail. Returns this for chaining.
user.switchEmail('verified@example.com')Static properties and methods
Section titled "Static properties and methods"emailVerificationTokensDbEmailTokensProviderThe token provider instance attached to the model. You can use it directly for lower-level token operations.
const tokens = await User.emailVerificationTokens.all(user)
const lastCreated = await User.emailVerificationTokens.lastCreatedAt(user)
await User.emailVerificationTokens.delete(user, tokenId)verifyEmailstatic methodVerifies an email using a token value string. Runs inside a database transaction. Returns the user instance with the updated email.
Throws E_INVALID_EMAIL_TOKEN when the token is invalid, expired, the email is already taken by another user, or the user no longer has a matching unverifiedEmail.
const verifiedUser = await User.verifyEmail(tokenValue)
const redirectedUser = await User.verifyEmail(tokenValue, { redirectTo: '/login' })