Adding Advanced Email Validation to Auth0

Auth0 is a great service to use as an authentication system for your SaaS business. Their universal login looks great out of the box and provides the right customization features.

To guide your users even more during the user registration or sign up process, I usually want to provide immediate feedback regarding invalid or malicious email addresses.

New potential customers get a hint about a potential typo if the email address is invalid (e.g. mailbox or domain doesn't exist). This avoids confusion afterwards: Where is the confirmation email you promised?

It also protects your service from getting malicious sign-ups using known spammer domains or email addresses from disposable email services (here's how our disposable email checker detects them). Additionally, email addresses detected as spam traps are something you don't want to have on your list. ย 

In this article, we guide you through the process to connect the Email Validation Service CampaignKit with Auth0 to add email validation to your universal sign up page.

Creating a Custom Action

Navigate to your Auth0 Dashboard and click on the Actions menu on the left side to expand it. Inside the Actions menu, you find the item Library. Open it and select Create Action โ†’ Build from scratch to create a new custom action.

A modal window will open. Give your custom action a name.

As the trigger, select Pre User Registration to make sure our action will be invoked before the actual user registration.

We are going to use Node to implement our action. Select Node 22 as your runtime (if it's not already pre-selected). Node 22 comes with a built-in fetch, so the action needs no extra dependencies.

Click the Create button to create the custom action.

Implementing the custom action

After creating the custom action, the editor is shown. It assigns an empty function to the onExecutePreUserRegistration hook_._

Auth0 calls this function when a user submits the registration form and before the actual user is created.

The following code is the complete implementation to validate email addresses before a user is created. It rejects user registrations with invalid or malicious email addresses and shows a custom error message.

Paste the following code into the editor and click Save Draft:

/**
 * Validate the given email address using CampaignKit.
 */
const validateEmail = async (event) => {
  const response = await fetch('https://api.campaignkit.cc/v1/email/validate', {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${event.secrets.TOKEN}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ emails: [event.user.email] }),
    // Give up well before Auth0's 20 second limit for an action.
    signal: AbortSignal.timeout(5000),
  });

  if (!response.ok) {
    throw new Error(`CampaignKit API returned ${response.status}`);
  }

  return response.json();
};

const errorMessage = (result) => {
  const codes = result.description || [];

  if (result.didYouMean) {
    return `Did you mean ${result.didYouMean}? Please check your email address.`;
  }
  if (codes.includes('mailbox')) {
    return 'Provided email address does not exist. Please check for typos.';
  }
  if (codes.includes('blacklist')) {
    return 'Provided email address is blacklisted. Please use a different address.';
  }
  if (codes.includes('disposable')) {
    return 'Disposable email addresses are not supported. Please use a permanent email address for sign up.';
  }
  return 'Provided email address is invalid. Please check for typos.';
};

/**
 * Handler that will be called during the execution of a PreUserRegistration flow.
 *
 * @param {Event} event - Details about the context and user that is attempting to register.
 * @param {PreUserRegistrationAPI} api - Interface whose methods can be used to change the behavior of the signup.
 */
exports.onExecutePreUserRegistration = async (event, api) => {
  try {
    const { results = [] } = await validateEmail(event);
    const result = results[0]?.result;

    if (result && result.score < 3) {
      api.access.deny('invalid_email_address', errorMessage(result));
    }
  } catch (e) {
    // Fail open: errors and timeouts let the sign up through.
    console.log('Email validation failed', e.message);
  }
};

If the email address fails validation (a score below 3), the action denies the sign up and shows the user why. When CampaignKit suggests a correction for a typo in the domain, such as gmai.com, the message offers it. If the validation service can't be reached or takes longer than 5 seconds to answer, the action lets the sign up through, so an outage doesn't block new users.

The original 2022 example is still on GitHub for reference; the code above is the current version.

To learn more about the CampaignKit Email Validation API, go to our article Getting Started with the Email Validation API to learn more.

Defining the Secrets ๐Ÿ”‘

Before we can use our new custom action, we need to define the API token to access the CampaignKit API.

To get your API token, you need to create an account for CampaignKit.

In your custom action, click on the key symbol. Click Add Secret to add a new secret for your custom action.

As the key use the value TOKEN. Copy & Paste your API token as the value.

Click the Create button to create the secret.

Click the Deploy button to publish your new custom action. It will only be available for your account.

Your new custom action is now ready to use. Let's continue to the last step and add it to the workflow.

Adding the Custom Action to your Pre User Registration Workflow

Now it's time to add your email validation to your user registration.

Navigate to Actions->Flow using the left menu. Click on the Pre User Registration item to open the workflow editor.

On the right side, click on the Custom tab. You should see your newly created action.

Drag & Drop your custom action into the flow, between the Start and Complete nodes.

Click the Apply button to put your changes live! ๐Ÿฅณ

Testing your registration form ๐Ÿงช

To test your integration, navigate to your signup page. To see all validations in action, you can test with the following email addresses:

  • โŒ Use an email address from a disposable email service like 10minut.xyz.
  • โŒ Use an email address with a non-existing domain.
  • โŒ Use an email address that doesn't exist (e.g. sdapofkaspodfposdkf@gmail.com)
  • โœ”๏ธ Use a valid email address

In case something goes wrong, navigate to Monitoring -> Logs to find more details about the issue.

Conclusion

A great onboarding experience starts with the registration page. Helping your users to detect typos in their email addresses saves them from weird issues and additional work to recover later.

As a SaaS owner/operator, you want to reject malicious user registration instantly. Validating the email addresses against common blacklists is a great approach.

If you want to learn more about how email validation works, read our article Email Verifier - Validate and Clean Email Addresses.

Join 1,000+ CompaniesImproving Email Deliverability

Start with 200 free validations. Upgrade only when you're ready.

No credit card required โ€ข Cancel anytime