NuxtZzle Logo

NuxtZzle starterkit | Nuxt Better Auth - How to implement user verification

LLeamsigc
NuxtZzle starterkit |  Nuxt Better Auth - How to implement user verification
  • But we need to trigger that email verification.

In the lib/auth.ts file, we need to add the following code:

emailVerification: {
    async sendVerificationEmail(user, url) {
        await sendUserVerificationEmail(user, url);
    },
    sendOnSignUp: true,
},

Where the sendUserVerificationEmail function is defined in the /server/utils/email file, in this function we will handle the following:

  1. Create the template for the email using mjml
  2. We pass the user information to the template generation plus the url that will containt eh verification link
  3. We send the email using the Mailgun API

Note Please make sure that you have the following environment variables set in your .env file:

  • MAILGUN_API_KEY
  • MAILGUN_DOMAIN
  • MAIL_FROM_EMAIL

We will need to update our lib/auth.ts file.

emailAndPassword: {
    requireEmailVerification: true
}

Overview of the user registration flow:

  1. User sign up
  2. We send a verification email
  3. User clicks on the link in the email to verify his email address
  4. User try to login

If the user try to login with out verifying his email address, the login will fail.

We will handle that in the /pages/login.vue file. By showing a message to the user that he need to verify his email address.

When the user submits the form to login we just need to handle the onError from the signIn.email function.

 await signIn.email({
    //Rest of the code here...
    fetchOptions: {
      onError: (context) => {
        toast({
          title: "Please try again",
          description: context?.error?.message || "Please check your email and password",
          variant: "destructive",
        });
      },
    },
  });

This will display a toast message to the user that he need to verify his email address or the error message generated by the Better Auth .

Note

When the user try to register with a existing email address

A more generic error message will be better. that way we don't show if the email is in out system, but it will be better to send a verification email base on the existing email address. and let the user know that a new registration attempt has been made.

The email for the verification is the following:

Email verification screenshot