Our authentication system is built on Next.js App Router with Auth.js (formerly NextAuth), providing a comprehensive solution for user authentication including OAuth providers, email/password login, two-factor authentication, email verification, and password reset functionality. It's designed with multi-tenant architecture in mind, ensuring secure user isolation across different schools and organizations.
Our authentication module delivers enterprise-grade security with a developer-friendly experience:
Our authentication system follows a layered architecture that prioritizes security, scalability, and developer experience:
The foundation of our authentication system consists of several key files that work together to provide a robust authentication experience:
src/auth.ts – Main Auth.js configuration with callbacks and session managementsrc/auth.config.ts – Provider configurations for Google, Facebook, and Credentialssrc/middleware.ts – Auth-based route protection with intelligent public route handlingsrc/routes.ts – Route definitions for authentication and public access patternssrc/next-auth.d.ts – TypeScript declarations for extended user types and session dataOur authentication components are organized for maximum reusability and maintainability:
Core Components (src/components/auth/)
user.ts – User database queries with multi-tenant supportuser-info.tsx – User information display componentuser-button.tsx – User dropdown/menu button with role-based optionssocial.tsx – OAuth provider login buttons with consistent stylinglogout-button.tsx – Secure logout functionality with session cleanuplogin-button.tsx – Login trigger button with provider selectionrole-gate.tsx – Role-based access control component for UI protectioncard-wrapper.tsx – Authentication form wrapper with consistent stylingheader.tsx – Authentication form headers with branding supportback-button.tsx – Navigation back button for form flowsform-error.tsx – Error message display with user-friendly formattingform-success.tsx – Success message display for positive feedbackvalidation.ts – Zod schemas for comprehensive form validationtokens.ts – Token generation and management utilitiesmail.ts – Email sending functionality with template supportauth.ts – Auth utility functions for common operationsaccount.ts – Account management utilitiesadmin-action.ts – Admin-specific actions and permissionsuse-current-user.ts – Hook for current user data with cachinguse-current-role.ts – Hook for current user role with real-time updatesFeature-Specific Directories
login/ – Complete login form and server actionsjoin/ – User registration form and validation actionsreset/ – Password reset request components and flowspassword/ – Password management and reset functionalityverification/ – Email verification and 2FA componentserror/ – Comprehensive error handling componentssetting/ – User settings and profile managementOur authentication system is built with multi-tenancy as a first-class concern, ensuring secure isolation between different organizations:
schoolId fieldOur database layer is optimized for multi-tenant operations:
getUserByEmail() uses findFirst() to handle multi-tenant email uniquenessgetUserById() provides secure user lookups by ID with school isolationOur middleware implements an intelligent route protection system that balances security with accessibility:
The system automatically handles public documentation routes:
// All /docs routes are automatically public
pathname.startsWith("/docs/")This elegant solution ensures all documentation routes are public by default without requiring manual configuration updates when adding new docs pages.
/dashboard, /project, /task, etc.) require authenticationRoleGate componentOur authentication system requires specific environment variables for full functionality:
# Core Authentication
AUTH_SECRET=your_auth_secret
# OAuth Providers
GOOGLE_CLIENT_ID=your_google_client_id
GOOGLE_CLIENT_SECRET=your_google_client_secret
FACEBOOK_CLIENT_ID=your_facebook_client_id
FACEBOOK_CLIENT_SECRET=your_facebook_client_secret
# Email Services
RESEND_API_KEY=your_resend_api_key
# Application URLs
NEXT_PUBLIC_APP_URL=http://localhost:3000Use the auth() function from your route handlers to protect server-side routes:
import { auth } from "@/auth";
export default async function ProtectedPage() {
const session = await auth();
if (!session) {
// Handle unauthorized access
redirect("/login");
}
return <div>Protected Content</div>;
}Use our provided hooks for seamless client-side authentication:
"use client";
import { useCurrentUser } from "@/components/auth/use-current-user";
export default function UserComponent() {
const user = useCurrentUser();
return <div>Hello, {user?.name}</div>;
}Implement granular permissions using the RoleGate component:
import { RoleGate } from "@/components/auth/role-gate";
import { UserRole } from "@prisma/client";
<RoleGate allowedRole={UserRole.ADMIN}>
<AdminPanel />
</RoleGate>When deploying to Vercel, ensure proper configuration:
Environment Variables:
NEXTAUTH_URL to your production URL (https://yourdomain.com)NODE_ENV=production to environment variablesFacebook OAuth Configuration:
https://yourdomain.com/api/auth/callback/facebookBuild Configuration:
next.config.js with proper Prisma configurationvercel-build.js is correctly set up to generate Prisma clientschema.prisma has binaryTargets = ["native", "rhel-openssl-3.0.x"]To extend this authentication module for your specific needs:
auth.config.ts to include additional OAuth providersauth.ts callbacks for custom authentication flowssrc/components/auth/ following established patternsCommon issues and their solutions:
/api/auth/debug/facebook for Facebook OAuth debuggingThis authentication system provides a solid foundation for building secure, scalable applications with enterprise-grade user management capabilities.
On This Page
AuthenticationCore FeaturesArchitecture OverviewCore Authentication FilesComponent ArchitectureMulti-Tenant ArchitectureUser Model FeaturesDatabase QueriesRoute Protection StrategyPublic RoutesProtected RoutesEnvironment ConfigurationUsage PatternsProtected Route ImplementationClient Component IntegrationRole-Based Access ControlDeployment ConsiderationsVercel DeploymentExtending the ModuleTroubleshooting