How to Implement Email Verification in Next.js?

Introduction

Email verification is a crucial step in user registration processes, ensuring that users provide valid email addresses and confirm their identity. This guide demonstrates how to implement email verification in a Next.js application.

1. Overview

The email verification process typically involves.

  1. User registration.
  2. Sending a verification email with a unique token.
  3. User clicks on a link in the email to verify their address.
  4. Token validation and account activation.

2. Setup and Configuration
 

2.1 Install Required Packages

You’ll need packages for sending emails and managing tokens.

npm install nodemailer jsonwebtoken

2.2 Create Environment Variables

Configure your email service in .env.local.

EMAIL_HOST=smtp.example.com
EMAIL_PORT=587
[email protected]
EMAIL_PASS=your-email-password
JWT_SECRET=your_jwt_secret
NEXT_PUBLIC_BASE_URL=http://localhost:3000

3. Sending Verification Emails
 

3.1 Setup Nodemailer

Configure Nodemailer to send emails.

// lib/email.js
import nodemailer from 'nodemailer';
const transporter = nodemailer.createTransport({
  host: process.env.EMAIL_HOST,
  port: process.env.EMAIL_PORT,
  auth: {
    user: process.env.EMAIL_USER,
    pass: process.env.EMAIL_PASS,
  },
});
export const sendVerificationEmail = async (email, token) => {
  const verificationUrl = `${process.env.NEXT_PUBLIC_BASE_URL}/verify-email?token=${token}`;
  await transporter.sendMail({
    from: process.env.EMAIL_USER,
    to: email,
    subject: 'Email Verification',
    html: `<p>Please verify your email by clicking on the link: <a href="${verificationUrl}">Verify Email</a></p>`,
  });
};

3.2 Generate and Send Token

Create an API route to handle user registration and send the verification email.

// pages/api/register.js
import jwt from 'jsonwebtoken';
import { sendVerificationEmail } from '../../lib/email';
export default async function handler(req, res) {
  if (req.method === 'POST') {
    const { email } = req.body;
    // Generate a verification token
    const token = jwt.sign({ email }, process.env.JWT_SECRET, { expiresIn: '1h' });
    // Send verification email
    await sendVerificationEmail(email, token);
    res.status(200).json({ message: 'Verification email sent' });
  } else {
    res.status(405).json({ message: 'Method not allowed' });
  }
}

4. Verifying the Email
 

4.1 Create a Verification Page

Create a page to handle the email verification.

// pages/verify-email.js
import { useRouter } from 'next/router';
import jwt from 'jsonwebtoken';
import { useEffect } from 'react';
const VerifyEmail = () => {
  const router = useRouter();
  const { token } = router.query;
  const verifyToken = async () => {
    try {
      jwt.verify(token, process.env.JWT_SECRET);
      // Activate user account here (e.g., update database)
      console.log('Email verified');
    } catch (error) {
      console.error('Invalid or expired token');
    }
  };
  useEffect(() => {
    if (token) verifyToken();
  }, [token]);
  return <div>Verifying email...</div>;
};
export default VerifyEmail;

4.2 Handle Token Validation

In the verify-email.js page, validate the token and perform account activation, such as updating the user’s status in the database.

5. Best Practices

  • Security: Ensure tokens are secure and have an expiration time. Use HTTPS for email links.
  • User Experience: Provide clear messages and instructions on the verification page.
  • Error Handling: Handle errors gracefully, such as expired or invalid tokens.

Summary

Implementing email verification in Next.js involves setting up email sending, generating and validating tokens, and creating a user-friendly verification process. By following this guide, you can ensure that users complete the registration process with verified email addresses, enhancing the security and integrity of your application.