├── .eslintrc.json
├── src
├── app
│ ├── favicon.ico
│ ├── extra
│ │ └── page.tsx
│ ├── page.tsx
│ ├── api
│ │ └── auth
│ │ │ └── [...nextauth]
│ │ │ ├── route.ts
│ │ │ └── options.ts
│ ├── context
│ │ └── AuthProvider.tsx
│ ├── denied
│ │ └── page.tsx
│ ├── server
│ │ └── page.tsx
│ ├── globals.css
│ ├── components
│ │ ├── Navbar.tsx
│ │ └── UserCard.tsx
│ ├── layout.tsx
│ └── client
│ │ └── page.tsx
└── middleware.ts
├── postcss.config.js
├── next.config.js
├── .gitignore
├── tailwind.config.js
├── next-auth.d.ts
├── public
├── vercel.svg
└── next.svg
├── package.json
├── tsconfig.json
└── README.md
/.eslintrc.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "next/core-web-vitals"
3 | }
4 |
--------------------------------------------------------------------------------
/src/app/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gitdagray/next-auth-role-based/HEAD/src/app/favicon.ico
--------------------------------------------------------------------------------
/postcss.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | plugins: {
3 | tailwindcss: {},
4 | autoprefixer: {},
5 | },
6 | }
7 |
--------------------------------------------------------------------------------
/src/app/extra/page.tsx:
--------------------------------------------------------------------------------
1 | export default async function ExtraPage() {
2 |
3 | return
Extra Page!
4 |
5 | }
--------------------------------------------------------------------------------
/src/app/page.tsx:
--------------------------------------------------------------------------------
1 |
2 |
3 | export default async function Home() {
4 |
5 | return (
6 | Public Home Page
7 | )
8 | }
9 |
--------------------------------------------------------------------------------
/src/app/api/auth/[...nextauth]/route.ts:
--------------------------------------------------------------------------------
1 | import NextAuth from 'next-auth'
2 | import { options } from './options'
3 |
4 | const handler = NextAuth(options)
5 |
6 | export { handler as GET, handler as POST }
--------------------------------------------------------------------------------
/src/app/context/AuthProvider.tsx:
--------------------------------------------------------------------------------
1 | 'use client'
2 |
3 | import { SessionProvider } from 'next-auth/react'
4 |
5 | export default function AuthProvider({ children }: {
6 | children: React.ReactNode
7 | }) {
8 | return (
9 |
10 | {children}
11 |
12 | )
13 | }
14 |
--------------------------------------------------------------------------------
/next.config.js:
--------------------------------------------------------------------------------
1 | /** @type {import('next').NextConfig} */
2 | const nextConfig = {
3 | images: {
4 | remotePatterns: [
5 | {
6 | protocol: 'https',
7 | hostname: 'avatars.githubusercontent.com',
8 | port: '',
9 | pathname: '/u/**',
10 | },
11 | ],
12 | },
13 | }
14 |
15 | module.exports = nextConfig
16 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2 |
3 | # dependencies
4 | /node_modules
5 | /.pnp
6 | .pnp.js
7 |
8 | # testing
9 | /coverage
10 |
11 | # next.js
12 | /.next/
13 | /out/
14 |
15 | # production
16 | /build
17 |
18 | # misc
19 | .DS_Store
20 | *.pem
21 |
22 | # debug
23 | npm-debug.log*
24 | yarn-debug.log*
25 | yarn-error.log*
26 |
27 | # local env files
28 | .env*.local
29 |
30 | # vercel
31 | .vercel
32 |
33 | # typescript
34 | *.tsbuildinfo
35 | next-env.d.ts
36 |
--------------------------------------------------------------------------------
/src/app/denied/page.tsx:
--------------------------------------------------------------------------------
1 | import Link from "next/link"
2 |
3 | export default function Denied() {
4 | return (
5 |
6 | Access Denied
7 | You are logged in, but you do not have the
8 | required access level to view this page.
9 |
10 | Return to Home Page
11 |
12 | )
13 | }
--------------------------------------------------------------------------------
/tailwind.config.js:
--------------------------------------------------------------------------------
1 | /** @type {import('tailwindcss').Config} */
2 | module.exports = {
3 | content: [
4 | './src/pages/**/*.{js,ts,jsx,tsx,mdx}',
5 | './src/components/**/*.{js,ts,jsx,tsx,mdx}',
6 | './src/app/**/*.{js,ts,jsx,tsx,mdx}',
7 | ],
8 | theme: {
9 | extend: {
10 | backgroundImage: {
11 | 'gradient-radial': 'radial-gradient(var(--tw-gradient-stops))',
12 | 'gradient-conic':
13 | 'conic-gradient(from 180deg at 50% 50%, var(--tw-gradient-stops))',
14 | },
15 | },
16 | },
17 | plugins: [],
18 | }
19 |
--------------------------------------------------------------------------------
/next-auth.d.ts:
--------------------------------------------------------------------------------
1 | // Ref: https://next-auth.js.org/getting-started/typescript#module-augmentation
2 |
3 | import { DefaultSession, DefaultUser } from "next-auth"
4 | import { JWT, DefaultJWT } from "next-auth/jwt"
5 |
6 | declare module "next-auth" {
7 | interface Session {
8 | user: {
9 | id: string,
10 | role: string,
11 | } & DefaultSession
12 | }
13 |
14 | interface User extends DefaultUser {
15 | role: string,
16 | }
17 | }
18 |
19 | declare module "next-auth/jwt" {
20 | interface JWT extends DefaultJWT {
21 | role: string,
22 | }
23 | }
--------------------------------------------------------------------------------
/public/vercel.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/src/app/server/page.tsx:
--------------------------------------------------------------------------------
1 | import { options } from "../api/auth/[...nextauth]/options"
2 | import { getServerSession } from "next-auth/next"
3 | import UserCard from "../components/UserCard"
4 | import { redirect } from "next/navigation"
5 |
6 | export default async function ServerPage() {
7 | const session = await getServerSession(options)
8 |
9 | if (!session) {
10 | redirect('/api/auth/signin?callbackUrl=/server')
11 | }
12 |
13 | return (
14 |
17 | )
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/src/app/globals.css:
--------------------------------------------------------------------------------
1 | @tailwind base;
2 | @tailwind components;
3 | @tailwind utilities;
4 |
5 | :root {
6 | --foreground-rgb: 0, 0, 0;
7 | --background-start-rgb: 214, 219, 220;
8 | --background-end-rgb: 255, 255, 255;
9 | }
10 |
11 | @media (prefers-color-scheme: dark) {
12 | :root {
13 | --foreground-rgb: 255, 255, 255;
14 | --background-start-rgb: 0, 0, 0;
15 | --background-end-rgb: 0, 0, 0;
16 | }
17 | }
18 |
19 | body {
20 | color: rgb(var(--foreground-rgb));
21 | background: linear-gradient(
22 | to bottom,
23 | transparent,
24 | rgb(var(--background-end-rgb))
25 | )
26 | rgb(var(--background-start-rgb));
27 | }
28 |
--------------------------------------------------------------------------------
/src/app/components/Navbar.tsx:
--------------------------------------------------------------------------------
1 | import Link from "next/link"
2 |
3 | export default function Navbar() {
4 | return (
5 |
15 | )
16 | }
17 |
18 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "next-auth-rbac",
3 | "version": "0.1.0",
4 | "private": true,
5 | "scripts": {
6 | "dev": "next dev",
7 | "build": "next build",
8 | "start": "next start",
9 | "lint": "next lint"
10 | },
11 | "dependencies": {
12 | "@types/node": "20.3.2",
13 | "@types/react": "18.2.14",
14 | "@types/react-dom": "18.2.6",
15 | "autoprefixer": "10.4.14",
16 | "eslint": "8.43.0",
17 | "eslint-config-next": "13.4.7",
18 | "next": "13.4.7",
19 | "next-auth": "^4.22.1",
20 | "postcss": "8.4.24",
21 | "react": "18.2.0",
22 | "react-dom": "18.2.0",
23 | "tailwindcss": "3.3.2",
24 | "typescript": "5.1.6"
25 | }
26 | }
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "es5",
4 | "lib": ["dom", "dom.iterable", "esnext"],
5 | "allowJs": true,
6 | "skipLibCheck": true,
7 | "strict": true,
8 | "forceConsistentCasingInFileNames": true,
9 | "noEmit": true,
10 | "esModuleInterop": true,
11 | "module": "esnext",
12 | "moduleResolution": "node",
13 | "resolveJsonModule": true,
14 | "isolatedModules": true,
15 | "jsx": "preserve",
16 | "incremental": true,
17 | "plugins": [
18 | {
19 | "name": "next"
20 | }
21 | ],
22 | "paths": {
23 | "@/*": ["./src/*"]
24 | }
25 | },
26 | "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
27 | "exclude": ["node_modules"]
28 | }
29 |
--------------------------------------------------------------------------------
/src/app/layout.tsx:
--------------------------------------------------------------------------------
1 | import './globals.css'
2 | import { Inter } from 'next/font/google'
3 | import Navbar from './components/Navbar'
4 | import AuthProvider from './context/AuthProvider'
5 |
6 | const inter = Inter({ subsets: ['latin'] })
7 |
8 | export const metadata = {
9 | title: 'NextAuth Tutorial',
10 | description: 'Learn NextAuth.js by Dave Gray',
11 | }
12 |
13 | export default function RootLayout({
14 | children,
15 | }: {
16 | children: React.ReactNode
17 | }) {
18 | return (
19 |
20 |
21 |
22 |
23 |
24 | {children}
25 |
26 |
27 |
28 |
29 | )
30 | }
31 |
--------------------------------------------------------------------------------
/src/app/client/page.tsx:
--------------------------------------------------------------------------------
1 | 'use client'
2 | // Remember you must use an AuthProvider for
3 | // client components to useSession
4 | import { useSession } from 'next-auth/react'
5 | import { redirect } from 'next/navigation'
6 | import UserCard from '../components/UserCard'
7 |
8 | export default function ClientPage() {
9 | const { data: session } = useSession({
10 | required: true,
11 | onUnauthenticated() {
12 | redirect('/api/auth/signin?callbackUrl=/client')
13 | }
14 | })
15 |
16 | // if (session?.user.role !== "admin"
17 | // && session?.user.role !== "manager") {
18 | // return Access Denied
19 | // }
20 |
21 | if (!session?.user) return
22 |
23 | return (
24 |
27 | )
28 | }
--------------------------------------------------------------------------------
/public/next.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/src/middleware.ts:
--------------------------------------------------------------------------------
1 | // Ref: https://next-auth.js.org/configuration/nextjs#advanced-usage
2 | import { withAuth, NextRequestWithAuth } from "next-auth/middleware"
3 | import { NextResponse } from "next/server"
4 |
5 | export default withAuth(
6 | // `withAuth` augments your `Request` with the user's token.
7 | function middleware(request: NextRequestWithAuth) {
8 | // console.log(request.nextUrl.pathname)
9 | // console.log(request.nextauth.token)
10 |
11 | if (request.nextUrl.pathname.startsWith("/extra")
12 | && request.nextauth.token?.role !== "admin") {
13 | return NextResponse.rewrite(
14 | new URL("/denied", request.url)
15 | )
16 | }
17 |
18 | if (request.nextUrl.pathname.startsWith("/client")
19 | && request.nextauth.token?.role !== "admin"
20 | && request.nextauth.token?.role !== "manager") {
21 | return NextResponse.rewrite(
22 | new URL("/denied", request.url)
23 | )
24 | }
25 | },
26 | {
27 | callbacks: {
28 | authorized: ({ token }) => !!token
29 | },
30 | }
31 | )
32 |
33 | // Applies next-auth only to matching routes - can be regex
34 | // Ref: https://nextjs.org/docs/app/building-your-application/routing/middleware#matcher
35 | export const config = { matcher: ["/extra", "/client", "/dashboard"] }
--------------------------------------------------------------------------------
/src/app/components/UserCard.tsx:
--------------------------------------------------------------------------------
1 | import Image from "next/image"
2 | import type { User } from "next-auth"
3 |
4 | type Props = {
5 | user: User,
6 | pagetype: string,
7 | }
8 |
9 | export default function Card({ user, pagetype }: Props) {
10 |
11 | //console.log(user)
12 |
13 | const greeting = user?.name ? (
14 |
15 | Hello {user?.name}!
16 |
17 | ) : null
18 |
19 | // const emailDisplay = user?.email ? (
20 | //
21 | // {user?.email}
22 | //
23 | // ) : null
24 |
25 | const userImage = user?.image ? (
26 |
34 | ) : null
35 |
36 | return (
37 |
38 | {greeting}
39 | {/* {emailDisplay} */}
40 | {userImage}
41 | {pagetype} Page!
42 | Role: {user?.role}
43 |
44 | )
45 | }
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # "NextAuth.js Role-Based Access Control"
2 |
3 | ## User Authorization & Protected Routes
4 |
5 | ### With Next.js App Router
6 |
7 | ---
8 |
9 | ### Author Links
10 |
11 | 👋 Hello, I'm Dave Gray.
12 |
13 | 👉 [My Courses](https://courses.davegray.codes/)
14 |
15 | ✅ [Check out my YouTube Channel with hundreds of tutorials](https://www.youtube.com/DaveGrayTeachesCode).
16 |
17 | 🚩 [Subscribe to my channel](https://bit.ly/3nGHmNn)
18 |
19 | ☕ [Buy Me A Coffee](https://buymeacoffee.com/DaveGray)
20 |
21 | 🚀 Follow Me:
22 |
23 | - [Twitter](https://twitter.com/yesdavidgray)
24 | - [LinkedIn](https://www.linkedin.com/in/davidagray/)
25 | - [Blog](https://yesdavidgray.com)
26 | - [Reddit](https://www.reddit.com/user/DaveOnEleven)
27 |
28 | ---
29 |
30 | ### Description
31 |
32 | 📺 [YouTube Video](https://youtu.be/ay-atEUGIc4) for this repository.
33 |
34 | ---
35 |
36 | ### 🎓 Academic Honesty
37 |
38 | **DO NOT COPY FOR AN ASSIGNMENT** - Avoid plagiarism and adhere to the spirit of this [Academic Honesty Policy](https://www.freecodecamp.org/news/academic-honesty-policy/).
39 |
40 | ---
41 |
42 | ### ⚙ Free Web Dev Tools
43 | - 🔗 [Google Chrome Web Browser](https://google.com/chrome/)
44 | - 🔗 [Visual Studio Code (aka VS Code)](https://code.visualstudio.com/)
45 | - 🔗 [ES7 React Snippets](https://marketplace.visualstudio.com/items?itemName=dsznajder.es7-react-js-snippets)
46 |
47 | ### 📚 References
48 | - 🔗 [NextAuth.js Official Site](https://next-auth.js.org/)
49 | - 🔗 [Next.js Official Site](https://nextjs.org/)
50 | - 🔗 [NextAuth.js - Advanced Middleware Configuration](https://next-auth.js.org/configuration/nextjs#advanced-usage)
51 | - 🔗 [NextAuth.js - Persisting the Role](https://authjs.dev/guides/basics/role-based-access-control#persisting-the-role)
52 | - 🔗 [NextAuth.js - TypeScript Module Augmentation](https://next-auth.js.org/getting-started/typescript#module-augmentation
53 | )
54 | - 🔗 [NextAuth.js - JWT & Session Callbacks](https://next-auth.js.org/configuration/callbacks#jwt-callback)
55 | - 🔗 [Next.js Rewrites](https://nextjs.org/docs/app/api-reference/functions/next-response#rewrite)
56 |
57 |
58 |
--------------------------------------------------------------------------------
/src/app/api/auth/[...nextauth]/options.ts:
--------------------------------------------------------------------------------
1 | import type { NextAuthOptions } from 'next-auth'
2 | import GitHubProvider from 'next-auth/providers/github'
3 | import CredentialsProvider from 'next-auth/providers/credentials'
4 | import { GithubProfile } from 'next-auth/providers/github'
5 |
6 | export const options: NextAuthOptions = {
7 | providers: [
8 | GitHubProvider({
9 | profile(profile: GithubProfile) {
10 | //console.log(profile)
11 | return {
12 | ...profile,
13 | role: profile.role ?? "user",
14 | id: profile.id.toString(),
15 | image: profile.avatar_url,
16 | }
17 | },
18 | clientId: process.env.GITHUB_ID as string,
19 | clientSecret: process.env.GITHUB_SECRET as string,
20 | }),
21 | CredentialsProvider({
22 | name: "Credentials",
23 | credentials: {
24 | username: {
25 | label: "Username:",
26 | type: "text",
27 | placeholder: "your-cool-username"
28 | },
29 | password: {
30 | label: "Password:",
31 | type: "password",
32 | placeholder: "your-awesome-password"
33 | }
34 | },
35 | async authorize(credentials) {
36 | // This is where you need to retrieve user data
37 | // to verify with credentials
38 | // Docs: https://next-auth.js.org/configuration/providers/credentials
39 | const user = { id: "42", name: "Dave", password: "nextauth", role: "manager" }
40 |
41 | if (credentials?.username === user.name && credentials?.password === user.password) {
42 | return user
43 | } else {
44 | return null
45 | }
46 | }
47 | })
48 | ],
49 | callbacks: {
50 | // Ref: https://authjs.dev/guides/basics/role-based-access-control#persisting-the-role
51 | async jwt({ token, user }) {
52 | if (user) token.role = user.role
53 | return token
54 | },
55 | // If you want to use the role in client components
56 | async session({ session, token }) {
57 | if (session?.user) session.user.role = token.role
58 | return session
59 | },
60 | }
61 | }
--------------------------------------------------------------------------------