- Install packages: npm install
- Create .env.local NEXTAUTH_SECRET=YOUR_VERY_SECRET_KEY_HERE
- Run the project: npm run dev
- Open `http://localhost:3000
This project includes a TypeScript reference file for Next.js:
/// <reference types="next" />
/// <reference types="next/image-types/global" />
import "./.next/dev/types/routes.d.ts";
// NOTE: This file should **not** be edited manually.
// For more information, see the official Next.js documentation:
// https://nextjs.org/docs/app/api-reference/config/typescript- Lets users log in using a username and password.
- Assigns a role to each user (like admin or user).
- Protects pages based on roles. For example:
- Admin pages → only admins can see.
- Normal user pages → both users and admins can see.
- Redirects users to the right page after login based on their role.
- Shows how to use middleware to protect pages globally.
- Next.js 16+ (App Router)
- React 19+
- NextAuth.js v5
- TypeScript 5
- TailwindCSS
app/→ all your pagescomponents/→ reusable React components (like Navbar)lib/protectedRoutes.ts→ defines which page needs which rolemiddleware.ts→ checks if the user is logged in and allowed to see the pageauth.ts→ configures NextAuth v5types/next-auth.d.ts→ adds a role property to user/session types
-
const users = [ { username: "adminuser", password: "adminpassword", role: "admin" }, { username: "normaluser", password: "userpassword", role: "user" }, ];
-
Admin can go to
/admin*pages. -
Normal user can go to
/normalUser*pages.
The middleware looks at each request:
- Checks if the page is protected.
- If yes, checks if the user is logged in.
- If the user is logged in, checks their role.
- Redirects to
/or/auth/signinif they aren’t allowed. - This makes sure only the right users see the right pages.