A production-ready Next.js boilerplate with built-in authentication, admin panel, user management, and comprehensive styling infrastructure.
- Authentication System - Secure JWT-based authentication with httpOnly cookies
- User Registration & Login - Complete user management with email/password validation
- Admin Panel - Full-featured admin panel with permission system
- User Management - Admin can view, edit, and manage users
- Protected Routes - Middleware-based route protection
- Role-Based Access - Admin and user roles with permission control
- Next.js 16+ - Latest App Router with TypeScript
- MongoDB Integration - Pre-configured MongoDB Atlas connection
- SCSS Modules - Custom styling infrastructure with variables and mixins
- Security Best Practices - Password hashing (bcrypt), JWT tokens, httpOnly cookies
- Responsive Design - Mobile-first responsive layouts
- Multi-Framework Templates - Claude Code integration with
.claude/directory
- Navigation with auth state
- Footer component
- Dashboard with user stats
- Admin panel with user management
- Welcome cards and info cards
- Auth forms (login/register)
- Reusable layouts (MainLayout, AuthLayout)
- Framework: Next.js 16+ with App Router
- Language: TypeScript
- Database: MongoDB with Mongoose
- Styling: SCSS Modules (NO Tailwind or CSS frameworks)
- Authentication: JWT + httpOnly cookies
- Security: bcrypt password hashing
- Sanitization: DOMPurify for XSS protection
- Node.js 18+ (Download)
- MongoDB Atlas account (Create free account)
-
Clone or download this repository:
git clone <your-repo-url> cd nextjs-auth-boilerplate
-
Install dependencies:
npm install
-
Set up environment variables:
# Copy the example env file cp .env.example .env.local -
Configure MongoDB:
Create a MongoDB Atlas database and get your connection string:
- Go to MongoDB Atlas
- Create a free cluster
- Set up database access (username/password)
- Set up network access (allow your IP or 0.0.0.0/0 for development)
- Get connection string from "Connect" → "Connect your application"
Update
.env.local:MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/your-database?retryWrites=true&w=majority JWT_SECRET=your-secure-random-string-here
-
Run the development server:
npm run dev
-
Open your browser: Navigate to http://localhost:3000
npm run dev # Start development server
npm run build # Build for production
npm run start # Start production server
npm run lint # Run ESLintnextjs-auth-boilerplate/
├── .claude/ # Claude Code templates & personas
│ ├── agents/ # Custom agent configurations
│ ├── docs/ # AI development documentation
│ └── personas/ # Framework-specific personas
├── src/
│ ├── app/ # Next.js App Router
│ │ ├── admin/ # Admin panel page
│ │ ├── dashboard/ # User dashboard
│ │ ├── login/ # Login page
│ │ ├── register/ # Registration page
│ │ ├── demo-auth/ # AuthLayout demo
│ │ ├── demo-main/ # MainLayout demo
│ │ ├── api/ # API routes
│ │ │ ├── auth/ # Authentication endpoints
│ │ │ └── admin/ # Admin endpoints
│ │ ├── layout.tsx # Root layout
│ │ └── page.tsx # Landing page
│ ├── components/ # Reusable components
│ │ ├── Navigation/ # Navigation bar
│ │ ├── Footer/ # Footer component
│ │ ├── LoginForm/ # Login form
│ │ ├── RegisterForm/ # Registration form
│ │ ├── DashboardHeader/ # Dashboard header
│ │ ├── AdminHeader/ # Admin panel header
│ │ ├── WelcomeCard/ # User welcome card
│ │ ├── InfoCards/ # Information cards
│ │ ├── StageCompleteCard/ # Stage completion card
│ │ ├── SearchBar/ # Search component
│ │ ├── Pagination/ # Pagination component
│ │ └── Toast/ # Toast notifications
│ ├── contexts/ # React contexts
│ │ └── AuthContext.tsx # Authentication context
│ ├── layouts/ # Layout components
│ │ ├── MainLayout/ # Main app layout
│ │ └── AuthLayout/ # Authentication layout
│ ├── lib/ # Utilities & configs
│ │ ├── mongodb.ts # MongoDB connection
│ │ ├── auth.ts # Auth utilities
│ │ └── logger.ts # Logging utility
│ ├── models/ # Database models
│ │ └── Admin.ts # User/Admin model
│ └── styles/ # SCSS infrastructure
│ ├── main.scss # Global styles
│ ├── _variables.scss # SCSS variables
│ ├── _mixins.scss # SCSS mixins
│ └── _themes.scss # Theme definitions
├── public/ # Static assets
├── .env.local # Local environment variables (create this)
├── .env.example # Environment template
├── package.json # Dependencies
└── README.md # This file
Create a .env.local file in the root directory with the following:
# MongoDB Connection
MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/your-database?retryWrites=true&w=majority
# JWT Secret (use a strong random string)
JWT_SECRET=your-secure-random-string-minimum-32-characters
# Optional: Node Environment
NODE_ENV=development
# Optional: App URL
NEXT_PUBLIC_APP_URL=http://localhost:3000Security Notes:
- Never commit
.env.localto version control - Use a strong, random JWT_SECRET (32+ characters)
- In production, use environment-specific values
-
Start the development server:
npm run dev
-
Register a new user:
- Navigate to
http://localhost:3000/register - Fill in the registration form
- Submit to create your account
- Navigate to
-
Manually promote to admin (via MongoDB):
- Go to MongoDB Atlas
- Find your user in the
userscollection - Update the
rolefield to"admin" - Update
isAdminfield totrue
-
Access admin panel:
- Navigate to
http://localhost:3000/admin - You should now see the admin panel
- Navigate to
- Change "YourApp" in
src/components/Navigation/Navigation.tsx:17 - Update meta tags in
src/app/layout.tsx - Update package name in
package.json
- Edit
src/app/page.tsxto customize the home page - Update feature cards to match your app's features
- Modify styles in
src/app/page.module.scss
- Edit
src/app/dashboard/page.tsxto add your dashboard content - Add new stat cards or remove existing ones
- Update dashboard styles in
src/app/dashboard/Dashboard.module.scss
// src/app/your-page/page.tsx
import { MainLayout } from '@/layouts';
export default function YourPage() {
return (
<MainLayout>
<div className="container">
<h1>Your Page</h1>
</div>
</MainLayout>
);
}// src/app/api/your-route/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { getUserFromToken } from '@/lib/auth';
export async function GET(req: NextRequest) {
const user = await getUserFromToken(req);
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
// Your logic here
return NextResponse.json({ data: 'Your data' });
}- Edit SCSS variables in
src/styles/_variables.scss - Modify theme colors in
src/styles/_themes.scss - Add new mixins in
src/styles/_mixins.scss - Update global styles in
src/styles/main.scss
- User submits registration form
- Backend validates email format and password strength
- Password is hashed with bcrypt (12 rounds)
- User is created in MongoDB
- JWT token is generated
- Token is stored in httpOnly cookie
- User is redirected to dashboard
- User submits login credentials
- Backend verifies email and password
- JWT token is generated
- Token is stored in httpOnly cookie
- User is redirected to dashboard
- Client-side:
useAuth()hook checks authentication state - Server-side: API routes validate JWT from cookies
- Automatic redirect to login if unauthenticated
The admin panel includes:
- User Management - View all users
- User Editing - Edit user details
- User Verification - Verify/unverify users
- Role Management - Promote/demote admin status
- Search & Filter - Find users quickly
- Pagination - Handle large user lists
GET /api/admin/users # Get all users (paginated)
GET /api/admin/users/[id] # Get single user
PUT /api/admin/users/[id] # Update user
POST /api/admin/users/[id]/verify # Toggle verification
This boilerplate uses SCSS Modules with a custom architecture:
- Colors, spacing, typography, breakpoints
- Customizable design tokens
- Flexbox utilities
- Button styles
- Card styles
- Responsive helpers
Each component has its own .module.scss file for scoped styling.
Global styles are in src/styles/main.scss and include reset, utilities, and theme setup.
This boilerplate includes a .claude/ directory with:
- Agents: Custom agent configurations for development workflows
- Docs: Comprehensive AI development documentation
- Personas: Framework-specific personas for different tech stacks
You can use Claude Code to:
- Generate new components following the project's patterns
- Add API routes with proper authentication
- Create new pages with the correct layouts
- Implement features while maintaining code style
This boilerplate includes a bi-directional sync system for the .claude/ directory:
📥 Pull updates FROM boilerplate:
# Preview what would change
npm run sync-claude:preview
# Sync Claude config from boilerplate
npm run sync-claude
# Force sync without confirmation
npm run sync-claude:force📤 Contribute improvements BACK to boilerplate:
# Share your agent improvements with other projects
npm run contribute-claudeBenefits:
- Get latest agent improvements from boilerplate
- Share your improvements back to boilerplate
- Keep all projects synced with best practices
- Build a shared knowledge base across projects
Documentation:
- CLAUDE_SYNC.md - Pull updates from boilerplate
- BIDIRECTIONAL_SYNC.md - Complete bi-directional workflow
- Password Hashing: bcrypt with 12 salt rounds
- JWT Tokens: Secure token generation with configurable expiry
- httpOnly Cookies: Prevents XSS token theft
- Input Sanitization: DOMPurify for user input
- Validation: Email format and password strength checks
- Protected Routes: Middleware-based authentication
- Admin Verification: Permission checks for admin actions
- Components in
src/components/ - Pages in
src/app/ - Utilities in
src/lib/ - Models in
src/models/ - Styles in
src/styles/and component modules
- Components: PascalCase (e.g.,
UserProfile.tsx) - Files: camelCase for utils, PascalCase for components
- SCSS: kebab-case classes (e.g.,
.user-profile) - Environment variables: UPPER_SNAKE_CASE
- Use TypeScript for type safety
- Define interfaces for data structures
- Avoid
anytype when possible
- Use SCSS modules for component styles
- Follow BEM-like naming for clarity
- Use CSS variables for theming
- Keep styles close to components
- Verify your connection string is correct
- Check if your IP is whitelisted in MongoDB Atlas
- Ensure database user has correct permissions
- Check JWT_SECRET is set in
.env.local - Verify cookies are being sent in requests
- Clear browser cookies and try again
- Delete
node_modules/and.next/folders - Run
npm installagain - Check for TypeScript errors with
npm run lint
- Check SCSS import paths
- Verify SCSS variables are defined
- Clear
.next/cache and rebuild
-
Push to GitHub:
git init git add . git commit -m "Initial commit" git remote add origin <your-repo-url> git push -u origin main
-
Deploy to Vercel:
- Go to vercel.com
- Import your GitHub repository
- Add environment variables (MONGODB_URI, JWT_SECRET)
- Deploy
-
Set up production MongoDB:
- Update MongoDB Atlas network access for Vercel IPs
- Use production connection string in Vercel environment variables
- Netlify: Use
npm run buildand deploy.next/folder - Railway: Connect GitHub repo and add environment variables
- DigitalOcean: Deploy with App Platform
This boilerplate includes demo pages for reference:
/demo-main- Demonstrates MainLayout usage/demo-auth- Demonstrates AuthLayout usage
You can remove these pages in production by deleting:
src/app/demo-main/src/app/demo-auth/
MIT License - Feel free to use this boilerplate for personal and commercial projects.
This is a boilerplate template. Feel free to fork and customize for your needs.
If you find bugs or have suggestions:
- Fork the repository
- Create a feature branch
- Make your changes
- Submit a pull request
For issues or questions:
- Check the troubleshooting section
- Review the code comments
- Check MongoDB Atlas documentation
- Review Next.js documentation
- Built with Next.js, React, and TypeScript
- Authentication inspired by industry best practices
- SCSS architecture follows modern component-based patterns
- Claude Code integration for AI-assisted development
- Core authentication system
- Admin panel with user management
- SCSS styling infrastructure
- MongoDB integration
- Protected routes
- Responsive design
- Claude Code integration
- Demo pages and documentation
Happy coding! 🚀