Version: 1.2.0
Status: Production Ready
Last Updated: October 5, 2025
A modern, secure attendance management system built with Next.js 15.5.4 featuring HTTP-only cookie authentication, 3-layer JWT validation, and server-side route protection.
npm installCopy the example environment file and update it with your backend API URL:
cp .env.local.example .env.localThen edit .env.local:
NEXT_PUBLIC_AUTH_API_URL=http://localhost:8000/api/v1/auth
NEXT_PUBLIC_API_URL=http://localhost:8000/api/v1
You can optionally disable Google Cloud Vision if you don't want to use that integration (for example, to avoid charges while developing). Add to `.env.local`:
GOOGLE_VISION_ENABLED=falsenpm run devOpen http://localhost:3000 with your browser to see the result.
You can start editing the page by modifying app/page.tsx. The page auto-updates as you edit the file.
This project follows a modular Next.js App Router layout with clear separation between pages, API proxies, feature components, and shared utilities. The structure below is an overview of the repository contents and where to look for important code.
attendify-frontend/
βββ src/
β βββ app/ # Next.js App Router: pages, layouts and server-side app-route proxies (app/api/*)
β β βββ api/ # Same-origin proxy routes and lightweight server APIs
β β βββ auth/ # Authentication pages (login, signup, logout)
β β βββ admin/ # Admin area pages and tools
β β βββ faculty/ # Faculty-facing pages
β β βββ student/ # Student area (classes, attendance, dashboard)
β β βββ layout.tsx # Root layout and top-level providers
β β
β βββ components/ # Reusable UI and feature components (shadcn UI wrappers, portals, camera components)
β β βββ student-portal/ # Student-facing components and sub-features (classes, attendance flow)
β β βββ ui/ # Generic UI building blocks
β β βββ ...
β β
β βββ lib/ # Shared libraries and API clients
β β βββ api/ # Client API helpers (classes, attendance, fetchClient)
β β βββ liveness-tests/ # Liveness detection utilities and helper algorithms
β β βββ utils/ # Formatting, avatars, detection helpers
β β
β βββ hooks/ # Custom React hooks (auth, toast, mobile helpers)
β βββ contexts/ # React context providers (AuthContext)
β βββ config/ # App configuration (routes, auth settings)
β βββ styles/ # Global CSS and Tailwind config
βββ public/ # Static assets (CSV, images, keys used in dev)
βββ docs/ # Project documentation and guides
βββ keys/ # Local developer keys (not for production)
βββ README.md
βββ package.json
βββ next.config.ts
βββ tsconfig.json
β β βββ auth/ # auth pages (login, signup) β β βββ admin/ # admin pages and subroutes β β βββ student/ # student area (classes, attendance) β β βββ faculty/ # faculty area β β βββ layout.tsx β β βββ page.tsx β β β βββ components/ # UI components and feature components β β βββ ui/ # shadcn UI wrappers β β βββ student-portal/ # student portal components (classes, take attendance) β β βββ face-camera.tsx # camera + liveness components β β βββ ... β β β βββ config/ # app configuration (routes, auth settings) β βββ contexts/ # React context providers (AuthContext) β βββ hooks/ # custom hooks (use-auth, use-toast, use-mobile) β βββ lib/ # utilities and API clients β β βββ api/ # client-side API helpers (classes, attendance, fetchClient) β β βββ middleware/ # server-side middleware helpers β β βββ utils/ # misc helpers (date, format, liveness) β β β βββ styles/ # global CSS β βββ docs/ # π Documentation and developer guides β βββ AUTHENTICATION_GUIDE.md β βββ MIDDLEWARE_GUIDE.md β βββ ARCHITECTURE_GUIDE.md β βββ .env.local.example βββ next.config.ts βββ tsconfig.json βββ package.json βββ README.md
---
## π Authentication System
### Overview
Production-ready authentication with **HTTP-only cookies**, **2-step OTP verification**, and **3-layer JWT validation** for maximum security and performance.
### π Complete Documentation
| Guide | Description | Lines |
| ------------------------------------------------------------- | ------------------------------------------------- | ----- |
| **[AUTHENTICATION_GUIDE.md](./docs/AUTHENTICATION_GUIDE.md)** | Complete auth system guide - flows, API, examples | 1000+ |
| **[MIDDLEWARE_GUIDE.md](./docs/MIDDLEWARE_GUIDE.md)** | 3-layer optimization, performance, security | 900+ |
| **[ARCHITECTURE_GUIDE.md](./docs/ARCHITECTURE_GUIDE.md)** | System architecture, modules, patterns | 1100+ |
### Authentication Features
#### π Security
- **HTTP-only Cookies** - Tokens inaccessible to JavaScript (XSS protection)
- **CSRF Protection** - SameSite cookie policy
- **Server-Side Validation** - Middleware validates before page loads
- **JWT Signature Verification** - Backend confirms token authenticity
- **User Existence Check** - Validates user still exists in database
#### β‘ Performance (v1.2.0)
- **3-Layer Validation System:**
- **Layer 1:** Client decode - Check expiration (0ms)
- **Layer 2:** In-memory cache - Recent validations (1ms, 90-99% hit rate)
- **Layer 3:** Backend API - Full validation (200ms, 1-10% of requests)
- **Result:** 20-200x faster authentication, 90-99% fewer backend calls
#### π― User Flows
- **Registration:** Two-step with email OTP verification
- **Login:** Flexible OTP (backend controlled) or direct token
- **Dashboard Access:** Automatic protection via middleware
- **Logout:** Secure cookie clearing
### Quick Usage Example
```tsx
"use client";
import { useAuth } from "@/hooks/use-auth";
export default function LoginPage() {
const { loginInitiate, loginVerify, isLoading, error } = useAuth();
// Step 1: Initiate login
const handleLogin = async () => {
const result = await loginInitiate({
username_or_email: "user@example.com",
password: "SecurePass123",
});
if (result.requiresOTP) {
// Show OTP input
setShowOTP(true);
}
// If no OTP required, automatically redirects to dashboard
};
// Step 2: Verify OTP (if required)
const handleVerifyOTP = async (code: string) => {
await loginVerify({
username_or_email: "user@example.com",
code: code,
});
// Automatically redirects to dashboard
};
return <div>{/* Your login form */}</div>;
}
It's as simple as adding a route to the array!
// 1. Open: src/config/routes.ts
export const PROTECTED_ROUTES = [
"/dashboard",
"/admin",
"/profile",
"/my-new-route", // β Add here
] as const;
// 2. That's it! Route is now automatically protected by middlewareWhat happens automatically:
- β
Middleware intercepts all requests to
/my-new-route - β Validates JWT token (3-layer system)
- β
Redirects to
/auth/loginif not authenticated - β Allows access if token is valid
- Next.js 15.5.4 - React framework with App Router
- React 19.1.0 - UI library
- TypeScript 5.x - Type safety
- Shadcn UI - Component library
- Tailwind CSS 4.1.14 - Utility-first styling
- Radix UI - Accessible primitives
- Lucide React - Icon library
- JWT - Token-based authentication
- Zod 4.1.11 - Schema validation
- HTTP-only Cookies - Secure token storage
- ESLint 9.x - Code linting
- Turbopack - Fast bundler
- TypeScript Strict Mode - Maximum type safety
Your backend must implement these endpoints:
| Method | Endpoint | Description |
|---|---|---|
POST |
/api/v1/auth/register/initiate |
Send OTP to email |
POST |
/api/v1/auth/register/verify |
Verify OTP, create account |
POST |
/api/v1/auth/login/initiate |
Login or request OTP |
POST |
/api/v1/auth/login/verify |
Verify OTP, get token |
GET |
/api/v1/users/me |
Get current user (for validation) |
These are handled automatically:
| Method | Endpoint | Description |
|---|---|---|
POST |
/api/auth/set-tokens |
Set HTTP-only cookies |
POST |
/api/auth/clear-tokens |
Clear cookies (logout) |
const {
// State
user, // Current user object or null
isLoading, // Loading state
isAuthenticated, // Authentication status
error, // Error message or null
// Methods
loginInitiate, // Step 1: Login (username/email + password)
loginVerify, // Step 2: Verify OTP code
registerInitiate, // Step 1: Register (email + username + password)
registerVerify, // Step 2: Verify OTP code
logout, // Clear tokens and redirect to login
refreshUser, // Reload user data
clearError, // Clear error state
} = useAuth();# Backend API URLs
NEXT_PUBLIC_AUTH_API_URL=http://localhost:8000/api/v1/auth
NEXT_PUBLIC_API_URL=http://localhost:8000/api/v1
# Optional: Override defaults
# NODE_ENV=production # Enables secure cookiesIf you don't have the backend available but want to develop the frontend, you can opt-in to a safe, local-only bypass of the middleware authentication checks.
Add the following to your .env.local (only for local development):
# When set to "1" or "true" (case-insensitive) and NODE_ENV is not "production",
# middleware will treat requests as authenticated so protected pages are accessible.
NEXT_PUBLIC_DEV_AUTH_BYPASS=1Notes and safety recommendations:
- This bypass is strictly opt-in and will only apply when
NODE_ENV !== 'production'. - Never enable this in production or CI environments.
- Use this for local UI development only. For more realistic testing consider using a mock API or MSW (Mock Service Worker).
- Remember to remove or set the variable to
0before committing or deploying.
Edit src/config/auth.ts to customize:
// Cookie settings
export const COOKIE_CONFIG = {
ACCESS_TOKEN: {
name: "access_token",
maxAge: 7 * 24 * 60 * 60, // 7 days
},
REFRESH_TOKEN: {
name: "refresh_token",
maxAge: 30 * 24 * 60 * 60, // 30 days
},
};
// Validation settings
export const VALIDATION_CONFIG = {
CACHE_TTL_MS: 60 * 1000, // Cache for 1 minute
CACHE_MAX_SIZE: 1000, // Max 1000 entries
FAILURE_CACHE_TTL_MS: 10 * 1000, // Cache failures for 10s
REQUEST_TIMEOUT_MS: 5 * 1000, // 5 second timeout
TOKEN_EXPIRY_BUFFER_SECONDS: 30, // 30 second buffer
};Edit src/config/routes.ts to customize:
// Routes that require authentication
export const PROTECTED_ROUTES = [
"/dashboard",
"/admin",
"/profile",
"/settings",
] as const;
// Routes that redirect authenticated users (login, signup)
export const AUTH_ROUTES = ["/auth/login", "/auth/signup"] as const;
// Routes accessible to everyone
export const PUBLIC_ROUTES = ["/", "/about", "/contact"] as const;# Development
npm run dev # Start development server (http://localhost:3000)
# Production
npm run build # Build for production
npm run start # Start production server
# Code Quality
npm run lint # Run ESLint
npm run type-check # Check TypeScript (if configured)| Scenario | Before (v1.1.0) | After (v1.2.0) | Improvement |
|---|---|---|---|
| Cache Hit | 200ms | 1ms | 200x faster |
| First Request | 200ms | 200ms | Same |
| 100 Requests | 20 seconds | 0.3 seconds | 66x faster |
| Backend Calls | 100 | 1-10 | 90-99% reduction |
- First Request: Validates with backend (200ms), caches result
- Subsequent Requests (within 1 min): Returns cached result (1ms)
- After Cache Expires: Re-validates with backend, updates cache
- β Tokens stored in HTTP-only cookies (not localStorage)
- β JavaScript cannot access tokens (XSS protection)
- β Automatic transmission with requests
- β Secure flag in production (HTTPS only)
- β Next.js middleware validates before page loads
- β Cannot bypass with browser DevTools
- β Validates JWT signature with backend
- β Confirms user still exists
- β
SameSite cookie policy (
lax) - β Prevents cross-site request forgery
- β Cookies not sent on cross-origin POST
- β Password validation (min 8 chars, uppercase, lowercase, number)
- β OTP verification for sensitive operations
- β Token expiration handling
- β Automatic logout on invalid token
- Next.js Documentation - Learn about Next.js features and API
- Learn Next.js - Interactive Next.js tutorial
- Next.js GitHub - Source code and issues
- AUTHENTICATION_GUIDE.md - Complete authentication guide
- MIDDLEWARE_GUIDE.md - Middleware optimization guide
- ARCHITECTURE_GUIDE.md - System architecture guide
- v1.2.0 Release Notes - Latest release details
The easiest way to deploy is using the Vercel Platform:
- Push your code to GitHub
- Import repository in Vercel
- Add environment variables:
NEXT_PUBLIC_AUTH_API_URL=https://your-backend.com/api/v1/auth NEXT_PUBLIC_API_URL=https://your-backend.com/api/v1 - Deploy!
Important: Ensure your backend:
- β Implements required API endpoints
- β Configures CORS for your frontend domain
- β
Has
/api/v1/users/meendpoint for validation
- Environment variables configured
- Backend API accessible
- CORS configured for frontend domain
- HTTPS enabled (required for secure cookies)
-
/api/v1/users/meendpoint working - OTP email delivery configured
- Error tracking setup (Sentry, etc.)
- Performance monitoring (Vercel Analytics, etc.)
- β HTTP-only cookie authentication
- β 3-layer JWT validation (20-200x faster)
- β Server-side route protection
- β Modular configuration layer
- β Consolidated documentation (3 comprehensive guides)
- β Fixed login redirect bug
- β Initial production release
- β Two-step authentication (OTP)
- β Registration with email verification
- β localStorage-based token management
- β Protected routes
- β Comprehensive documentation
Contributions are welcome! Please follow these steps:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
This project is licensed under the MIT License.
- Documentation: Check the guides in
/docs - Issues: Open an issue on GitHub
- Email: Contact the development team
Built with β€οΈ by the Attendify Team