A minimalist Next.js project demonstrating route protection with JWT authentication for admin pages.
This starter provides a clean separation between public and admin pages with a simple JWT-based authentication system. It's ideal for:
- Projects requiring protected admin areas
- Sites with pre-defined admin users (no registration needed)
- Simple authentication without complex user management
Default credentials: username: abc
| password: xyz
- Route Protection: Only authenticated users can access admin pages
- JWT Authentication: Secure token-based auth with 30-day expiration
- Middleware-based Protection: All
/admin/*
routes automatically protected - Smart Redirects: Authenticated users are redirected from login to admin dashboard
- Modern Stack: Built with Next.js 15+, React 19+, and TailwindCSS 4
- TypeScript: Fully typed for better developer experience
src/
├── app/
│ ├── (admin)/admin/ # Protected admin routes
│ │ ├── login/ # Admin login page
│ │ └── page.tsx # Admin dashboard
│ ├── (site)/ # Public pages
│ ├── api/auth/ # Authentication API endpoints
│ │ ├── login/ # Login API
│ │ └── logout/ # Logout API
│ └── components/ # Shared components
├── middleware.ts # Route protection logic
The middleware (src/middleware.ts
) intercepts requests to /admin/*
routes:
- Unauthenticated users trying to access
/admin/*
are redirected to/admin/login
- Authenticated users trying to access
/admin/login
are redirected to/admin/
- Authentication is verified by checking the JWT token in cookies
- User submits credentials on the login page
- The
/api/auth/login
endpoint verifies credentials against environment variables - On success, a JWT token is generated and stored in an HTTP-only cookie
- The middleware validates this token for all admin route requests
-
Clone the repository
git clone https://github.com/C0ldSmi1e/nextjs-jwt-login-example.git cd nextjs-jwt-login-example
-
Install dependencies
npm install # or yarn install
-
Configure environment variables Create a
.env.local
file (see.env.example
):JWT_SECRET=your-secret-key ADMIN_USERS={"username1": "password1", "username2": "password2"}
-
Run the development server
npm run dev # or yarn dev