Automatically Resend Verification Email Upon Login when Link Expires

Last Updated: Sep 24, 2024

Overview

This article clarifies whether the email with the address verification link can be resent at the next login if the initial verification email link that was sent has expired.

Applies To

  • Address Verification Link
  • Email
  • Action

Solution

There is no out-of-the-box way to accomplish this. However, this can be achieved with an Action. In the Action, check if the email_verified attribute is set to true or false.

Here is an example:

const auth0 = require('auth0');

// Change this value based on your email verification link timout setting
const SEND_EMAIL_WAIT_IN_SECONDS = 120 

exports.onExecutePostLogin = async (event, api) => {
  const currentTime = Number(Date.now()) / 1000; // Currrent time in seconds
  const lastSentTime = event.user.app_metadata.lastVerificationEmailSentTime || 0;
  
  if (!event.user.email_verified && (currentTime - lastSentTime) > SEND_EMAIL_WAIT_IN_SECONDS) {
    const management = new auth0.ManagementClient({
      domain: event.secrets.domain,
      clientId: event.secrets.clientId,
      clientSecret: event.secrets.clientSecret
    });
    var params = {
      client_id: event.client.client_id,
      user_id: event.user.user_id
    };
    management.jobs.verifyEmail(params, function (err) {
      if (err) {
        // Handle error.
      }
    });

    // Store the time the verification email was sent in user's app_metadata
    api.user.setAppMetadata("lastVerificationEmailSentTime", currentTime);
  }
};

Remember to add the secrets (environment variables) and also the dependencies, in this case, the ‘auth0’ library, while using Management API in Actions.