A modern, production-ready authentication system for Next.js applications that seamlessly integrates with Laravel Sanctum API. Built with TypeScript, featuring beautiful UI components, state management, and comprehensive form validation.
- Complete Authentication Flow - Login, Register, and Logout functionality
- Modern UI Components - Built with shadcn/ui and Radix UI primitives
- Responsive Design - Mobile-first approach with Tailwind CSS
- State Management - Zustand for efficient state management with persistence
- Form Validation - Zod schema validation with React Hook Form
- TypeScript - Full type safety throughout the application
- Token Management - Automatic token handling and refresh
- API Integration - Axios-based HTTP client with interceptors
- Error Handling - Comprehensive error handling with user-friendly messages
- Modular Architecture - Clean, maintainable code structure
- Laravel-Inspired Structure - Follows Laravel conventions and architectural patterns
- Next.js 15.5.4 - React framework with App Router
- React 19.1.0 - UI library
- TypeScript 5 - Type safety and developer experience
- shadcn/ui - Modern component library
- Radix UI - Accessible component primitives
- Tailwind CSS 4 - Utility-first CSS framework
- Lucide React - Beautiful icons
- next-themes - Theme management
- Zustand 5.0.8 - Lightweight state management
- React Hook Form 7.65.0 - Performant forms
- Zod 4.1.12 - Schema validation
- @hookform/resolvers - Form validation integration
- Axios 1.12.2 - HTTP client
- SWR 2.3.6 - Data fetching and caching
- ESLint - Code linting
- PostCSS - CSS processing
- Turbopack - Fast bundling
- Node.js 18+
- npm or yarn
- Laravel backend with Sanctum configured
-
Clone the repository
git clone https://github.com/hasemon/nextjs-laravel-authkit.git cd nextjs-laravel-authkit -
Install dependencies
npm install # or yarn install -
Environment Setup Create a
.env.localfile in the root directory:NEXT_PUBLIC_API_URL=http://localhost:8000/api NEXT_PUBLIC_APP_NAME=Your App Name
-
Run the development server
npm run dev # or yarn dev -
Open your browser Navigate to http://localhost:3000
src/
βββ app/ # Next.js App Router
β βββ (auth)/ # Authentication routes
β β βββ login/ # Login page
β β βββ register/ # Register page
β βββ globals.css # Global styles
β βββ layout.tsx # Root layout
β βββ page.tsx # Home page
βββ components/ # React components
β βββ pages/auth/ # Authentication forms
β βββ ui/ # shadcn/ui components
β βββ app-logo.tsx # Application logo
β βββ nav-bar.tsx # Navigation component
β βββ user-dropdown.tsx # User menu
βββ lib/ # Utility libraries
β βββ request.ts # Axios configuration
β βββ useAuth.ts # Authentication hooks
β βββ useGet.ts # Data fetching hooks
β βββ utils.ts # Utility functions
βββ routes/ # Route definitions
β βββ api.ts # API endpoints
β βββ web.ts # Web routes
βββ store/ # State management
β βββ useAuthStore.ts # Authentication store
βββ types/ # TypeScript definitions
βββ nav-link-type.d.ts
This project is heavily inspired by Laravel's elegant architecture and follows many of its conventions:
- Controllers β
useAuth.ts(similar to Laravel's AuthController) - Models β
useAuthStore.ts(state management like Eloquent models) - Routes β
api.tsandweb.ts(mirroring Laravel's route files) - Middleware β Request/Response interceptors in
request.ts - Services β Authentication service pattern in
useAuth.ts
- Service Layer - Authentication logic separated into services
- Repository Pattern - State management with Zustand stores
- Middleware - Axios interceptors for request/response handling
- Form Requests - Zod validation schemas (similar to Laravel Form Requests)
- Resource Controllers - API endpoint organization
- Blade Components β React Components with similar structure
- Token-based Authentication - Seamless integration with Laravel Sanctum
- CSRF Protection - Built-in CSRF token handling
- Session Management - Persistent authentication state
- API Routes - RESTful endpoint structure matching Laravel conventions
This approach makes the codebase familiar to Laravel developers while leveraging the power of React and Next.js.
Your Laravel backend should have the following API endpoints:
// routes/api.php
Route::post('/register', [AuthController::class, 'register']);
Route::post('/login', [AuthController::class, 'login']);
Route::post('/logout', [AuthController::class, 'logout'])->middleware('auth:sanctum');
Route::get('/user', [AuthController::class, 'user'])->middleware('auth:sanctum');Update the API endpoints in src/routes/api.ts:
const api = {
auth: {
user: () => "user",
register: () => "register",
login: () => "login",
logout: () => "logout",
},
};import { useAuth } from "@/lib/useAuth";
// Login
const handleLogin = async (credentials) => {
try {
await useAuth.login(credentials);
// User is now logged in
} catch (error) {
// Handle error
}
};
// Register
const handleRegister = async (userData) => {
try {
await useAuth.register(userData);
// User is automatically logged in
} catch (error) {
// Handle error
}
};
// Logout
const handleLogout = async () => {
await useAuth.logout();
// User is now logged out
};
// Check authentication status
const isAuthenticated = useAuth.isAuthenticated();
const currentUser = useAuth.getCurrentUser();import useAuthStore from "@/store/useAuthStore";
function MyComponent() {
const { token, user, setAuth, clearAuth } = useAuthStore();
// Access authentication state
const isLoggedIn = !!token;
// Update authentication state
setAuth(token, user);
// Clear authentication state
clearAuth();
}The project includes pre-built form components with validation:
LoginForm- User login with email/passwordRegisterForm- User registration with validation- Form validation using Zod schemas
- Error handling and loading states
Built with shadcn/ui, the project includes:
- Form Components - Input, Button, Field with validation
- Layout Components - Card, Navigation, Dropdown
- Feedback Components - Toast notifications, Spinner
- Accessibility - ARIA labels, keyboard navigation
- Token Management - Automatic token storage and refresh
- Request Interceptors - Automatic Bearer token attachment
- Response Interceptors - Handle token expiration
- CSRF Protection - Laravel Sanctum CSRF tokens
- Input Validation - Client and server-side validation
- Mobile-first approach
- Responsive navigation
- Touch-friendly interfaces
- Optimized for all screen sizes
- Push your code to GitHub
- Connect your repository to Vercel
- Set environment variables in Vercel dashboard
- Deploy automatically
The project can be deployed to any platform that supports Next.js:
- Netlify
- AWS Amplify
- Railway
- DigitalOcean App Platform
We welcome contributions! Please see our Contributing Guidelines for details.
- 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 - see the LICENSE file for details.
- Next.js - The React framework
- Laravel Sanctum - API authentication
- shadcn/ui - Beautiful UI components
- Zustand - State management
- Radix UI - Accessible components
If you have any questions or need help, please:
- Open an issue on GitHub
- Check the documentation
- Join our community discussions
Made with β€οΈ for the open source community