8
Fullstack

Auth 2FA

A secure, full-stack two-factor authentication component with email verification, progressive UI, and seamless Next.js server actions integration.

Two-Factor Authentication Form

A comprehensive, secure two-factor authentication component that provides email-based verification with a beautiful, progressive user interface. Features real-time validation, automatic code expiration, and seamless integration with Next.js server actions.

Two-Factor Authentication Form Component
Loading component registry...

Installation

Install the component using the AxionsJS CLI:

npx axionjs-ui add two-factor-form

Configure your environment variables in .env:

# Database
DATABASE_URL="postgresql://username:password@localhost:5432/database_name"

# Email Configuration
EMAIL_SERVER_HOST="smtp.gmail.com"
EMAIL_SERVER_PORT="587"
EMAIL_SERVER_USER="your-email@gmail.com"
EMAIL_SERVER_PASSWORD="your-app-password"
EMAIL_FROM="Your App <your-email@gmail.com>"

# Authentication
AUTH_SECRET="your-auth-secret"
NEXT_PUBLIC_APP_URL="http://localhost:3000"

Set up Prisma schema and push to database:

npx prisma db push

The component includes complete database models for users, two-factor tokens, and confirmations. Email templates and server actions are pre-configured and ready to use.

Database Schema

Add the following models to your schema.prisma file:

schema.prisma
model User {
  id                    String                 @id @unique @default(cuid())
  name                  String?
  email                 String?                @unique
  image                 String?
  password              String?
  isTwoFactorEnabled    Boolean                @default(false)
  twoFactorConfirmation TwoFactorConfirmation?
  accounts              Account[]
 
  @@map("users")
}
 
model TwoFactorToken {
  id      String   @id @default(cuid())
  email   String
  token   String   @unique
  expires DateTime
 
  @@unique([email, token])
}
 
model TwoFactorConfirmation {
  id     String @id @default(cuid())
  userId String
  user   User   @relation(fields: [userId], references: [id], onDelete: Cascade)
 
  @@unique([userId])
}

Run npx prisma db push after adding the schema to apply changes to your database.

Usage

Import and use the TwoFactorForm component:

app/auth/2fa/page.tsx
"use client";
import { TwoFactorForm } from "@/components/two-factor-form";
 
export default function TwoFactorPage() {
  return (
    <div className="min-h-screen bg-gray-50 py-12">
      <div className="mx-auto max-w-xl px-4">
        <TwoFactorForm
          onSuccess={(email) => {
            console.log("2FA verified for:", email);
            // Redirect to dashboard or handle success
          }}
          onError={(error) => {
            console.error("2FA error:", error);
            // Handle error state
          }}
        />
      </div>
    </div>
  );
}

Key Features

Component Props

PropTypeDefault
onSuccess
(email: string) => void
undefined
onError
(error: string) => void
undefined
title
string
"Two-Factor Authentication"
description
string
"Secure your account with an additional layer of protection"
className
string
""

Server Actions

The component utilizes Next.js server actions for secure backend operations:

actions/two-factor-actions.ts
export const requestTwoFactorCode = async (
  values: { email: string }
): Promise<TwoFactorActionResult> => {
  const validatedFields = TwoFactorRequestSchema.safeParse(values);
  
  if (!validatedFields.success) {
    return { error: "Invalid email address" };
  }
 
  const { email } = validatedFields.data;
  
  // Generate and send 2FA token
  const twoFactorToken = await generateTwoFactorToken(email);
  await sendTwoFactorTokenEmail(email, twoFactorToken.token);
 
  return {
    success: "Verification code sent to your email",
    twoFactorRequired: true,
  };
};

Features:

  • Email validation with Zod schema
  • Automatic token cleanup (removes old tokens)
  • Secure 6-digit code generation
  • Professional email template delivery

Email Templates

The component includes a beautiful, responsive email template:

emails/two-factor-template.tsx
export const getTwoFactorEmailTemplate = (token: string) => {
  const html = `
    <!DOCTYPE html>
    <html>
      <head>
        <title>Two-Factor Authentication Code</title>
        <style>
          .container { max-width: 600px; margin: 40px auto; background: white; }
          .header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
          .code { font-size: 36px; font-weight: bold; letter-spacing: 8px; }
        </style>
      </head>
      <body>
        <div class="container">
          <div class="header">
            <h1>🔐 Two-Factor Authentication</h1>
          </div>
          <div class="content">
            <div class="code">${token}</div>
            <p>This code expires in 5 minutes.</p>
          </div>
        </div>
      </body>
    </html>
  `;
  
  return { html, text: `Your verification code: ${token}` };
};

Email Features:

  • Responsive design for all devices
  • Professional gradient styling
  • Clear, large verification code display
  • Security warnings and instructions
  • Plain text fallback for accessibility

Security Features

The Two-Factor Authentication Form implements multiple security layers:

  • Token Expiration: All codes expire after 5 minutes
  • Single Use: Tokens are deleted after successful verification
  • Rate Limiting: Prevents spam and abuse (configurable)
  • Secure Generation: Uses Node.js crypto for token generation
  • Input Validation: Comprehensive validation with Zod schemas
  • SQL Injection Protection: Prisma provides built-in protection

Always use HTTPS in production and ensure your email provider supports secure authentication.

Conclusion

The Two-Factor Authentication Form provides a complete, production-ready solution for adding email-based 2FA to your Next.js applications. With its progressive UI, comprehensive security features, and seamless server actions integration, it delivers both excellent user experience and robust security protection.

On this page