8
Fullstack

Auth Simple

A complete, secure authentication system with login, register, email verification, and password reset functionality built with Next.js server actions.

Simple Auth System

A comprehensive, production-ready authentication system that provides secure user management with email verification, password reset, and beautiful UI components. Built with Next.js server actions, Prisma, and modern security practices.

Simple Auth System Components
Loading component registry...

Installation

Install the component using the AxionJS CLI:

npx axionjs-ui add simple-auth

Configure your environment variables in .env:

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

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

# 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>"

Set up Prisma schema and push to database:

npx prisma db push
npx prisma generate

The component includes complete database models, email templates, server actions, and UI components. Everything is pre-configured for immediate use.

Database Schema

Add the following models to your schema.prisma file:

schema.prisma
model User {
  id            String    @id @default(cuid())
  name          String?
  email         String    @unique
  emailVerified DateTime?
  password      String?
  image         String?
  createdAt     DateTime  @default(now())
  updatedAt     DateTime  @updatedAt
  accounts      Account[]
 
  @@map("users")
}
 
model Account {
  id                String  @id @default(cuid())
  userId            String
  type              String
  provider          String
  providerAccountId String
  refresh_token     String?
  access_token      String?
  expires_at        Int?
  token_type        String?
  scope             String?
  id_token          String?
  session_state     String?
  user              User    @relation(fields: [userId], references: [id], onDelete: Cascade)
 
  @@unique([provider, providerAccountId])
  @@map("accounts")
}
 
model VerificationToken {
  id      String   @id @default(cuid())
  email   String
  token   String   @unique
  expires DateTime
 
  @@unique([email, token])
  @@map("verification_tokens")
}
 
model PasswordResetToken {
  id      String   @id @default(cuid())
  email   String
  token   String   @unique
  expires DateTime
 
  @@unique([email, token])
  @@map("password_reset_tokens")
}

Usage

app/auth/login/page.tsx
import { LoginForm } from "@/components/login-form";
 
export default function LoginPage() {
  return (
    <div className="min-h-screen flex items-center justify-center bg-gray-50">
      <LoginForm />
    </div>
  );
}

The LoginForm component includes:

  • Email and password validation
  • Secure credential verification
  • Automatic email verification check
  • Redirect handling with callback URLs
  • Loading states and error handling

Key Features

Server Actions

The authentication system uses Next.js server actions for secure backend operations:

actions/auth-actions.ts
export const login = async (
  values: z.infer<typeof LoginSchema>,
  callbackUrl?: string | null,
) => {
  const validatedFields = LoginSchema.safeParse(values);
  if (!validatedFields.success) {
    return { error: "Invalid fields!" };
  }
 
  const { email, password } = validatedFields.data;
  const existingUser = await getUserByEmail(email);
  
  if (!existingUser || !existingUser.password) {
    return { error: "Email does not exist!" };
  }
 
  const passwordsMatch = await verifyPassword(password, existingUser.password);
  
  if (!existingUser.emailVerified) {
    if (!passwordsMatch) {
      return { error: "Invalid credentials!" };
    }
    // Send verification email
    const verificationToken = await generateVerificationToken(existingUser.email);
    await sendVerificationEmail(verificationToken.email, verificationToken.token);
    return { success: "Confirmation email sent!" };
  }
 
  if (!passwordsMatch) {
    return { error: "Invalid credentials!" };
  }
 
  await signIn("credentials", {
    email,
    password,
    redirectTo: callbackUrl || DEFAULT_LOGIN_REDIRECT,
  });
 
  return { success: "Logged in!" };
};

Email Templates

The system includes professional, responsive email templates:

emails/verification-email.tsx
export default function VerificationEmail({ confirmLink }: { confirmLink: string }) {
  return (
    <Html>
      <Head />
      <Preview>Verify your email address</Preview>
      <Tailwind>
        <Body className="bg-white my-auto mx-auto font-sans">
          <Container className="border border-solid border-[#eaeaea] rounded my-[40px] mx-auto p-[20px] w-[465px]">
            <Section className="mt-[32px]">
              <Text className="text-black text-[24px] font-medium mb-[0] mt-[0] mx-[0]">
                Verify your email
              </Text>
              <Text className="text-black text-[14px] leading-[24px]">
                Click the button below to verify your email address.
              </Text>
              <Button
                className="bg-blue-600 rounded text-white font-medium py-[8px] px-[20px]"
                href={confirmLink}
              >
                Confirm Email
              </Button>
              <Hr className="border border-solid border-[#eaeaea] my-[26px] mx-[0] w-full" />
              <Text className="text-[#666666] text-[12px] leading-[24px]">
                This link will expire in 24 hours.
              </Text>
            </Section>
          </Container>
        </Body>
      </Tailwind>
    </Html>
  );
}

Security Features

The Simple Auth system implements comprehensive security measures:

  • Password Hashing: Secure bcrypt hashing with salt rounds
  • JWT Tokens: Secure session management with NextAuth.js
  • Email Verification: Mandatory email verification for new accounts
  • Token Expiration: Time-limited tokens for security (24h verification, 1h reset)
  • CSRF Protection: Built-in protection against cross-site request forgery
  • Input Validation: Comprehensive Zod schema validation
  • SQL Injection Protection: Prisma provides built-in protection
  • Rate Limiting: Configurable rate limiting for authentication endpoints

Always use HTTPS in production and ensure your email provider supports secure authentication. Consider implementing additional security measures like account lockout policies for production use.

Component Structure

The authentication system includes the following components:

  • LoginForm: Handles user login with email verification check
  • RegisterForm: User registration with automatic email verification
  • ResetForm: Password reset request form
  • NewPasswordForm: New password setting after reset
  • NewVerificationForm: Email verification handling
  • CardWrapper: Reusable card wrapper for consistent styling
  • FormError/FormSuccess: Standardized error and success message components

Conclusion

The Simple Auth system provides a complete, production-ready authentication solution for Next.js applications. With its comprehensive security features, beautiful UI components, and modern server actions integration, it offers both excellent developer experience and robust user authentication capabilities.

On this page