Full Code of gitdagray/next-auth-intro for AI

main 4281c170ac2e cached
20 files
10.5 KB
3.4k tokens
11 symbols
1 requests
Download .txt
Repository: gitdagray/next-auth-intro
Branch: main
Commit: 4281c170ac2e
Files: 20
Total size: 10.5 KB

Directory structure:
gitextract_gzu13coo/

├── .eslintrc.json
├── .gitignore
├── README.md
├── next.config.js
├── package.json
├── postcss.config.js
├── src/
│   ├── app/
│   │   ├── api/
│   │   │   └── auth/
│   │   │       └── [...nextauth]/
│   │   │           ├── options.ts
│   │   │           └── route.ts
│   │   ├── client/
│   │   │   └── page.tsx
│   │   ├── components/
│   │   │   ├── Navbar.tsx
│   │   │   └── UserCard.tsx
│   │   ├── context/
│   │   │   └── AuthProvider.tsx
│   │   ├── extra/
│   │   │   └── page.tsx
│   │   ├── globals.css
│   │   ├── layout.tsx
│   │   ├── page.tsx
│   │   └── server/
│   │       └── page.tsx
│   └── middleware.ts
├── tailwind.config.js
└── tsconfig.json

================================================
FILE CONTENTS
================================================

================================================
FILE: .eslintrc.json
================================================
{
  "extends": "next/core-web-vitals"
}


================================================
FILE: .gitignore
================================================
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js

# testing
/coverage

# next.js
/.next/
/out/

# production
/build

# misc
.DS_Store
*.pem

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# local env files
.env*.local

# vercel
.vercel

# typescript
*.tsbuildinfo
next-env.d.ts


================================================
FILE: README.md
================================================
# "NextAuth.js Login Authentication"

## With Next.js App Router

---

### Author Links

👋 Hello, I'm Dave Gray.

👉 [My Courses](https://courses.davegray.codes/)

✅ [Check out my YouTube Channel with hundreds of tutorials](https://www.youtube.com/DaveGrayTeachesCode).

🚩 [Subscribe to my channel](https://bit.ly/3nGHmNn)

☕ [Buy Me A Coffee](https://buymeacoffee.com/DaveGray)

🚀 Follow Me:

- [Twitter](https://twitter.com/yesdavidgray)
- [LinkedIn](https://www.linkedin.com/in/davidagray/)
- [Blog](https://yesdavidgray.com)
- [Reddit](https://www.reddit.com/user/DaveOnEleven)

---

### Description

📺 [YouTube Video](https://youtu.be/w2h54xz6Ndw) for this repository.

---

### 🎓 Academic Honesty

**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/).

---

### ⚙ Free Web Dev Tools
- 🔗 [Google Chrome Web Browser](https://google.com/chrome/)
- 🔗 [Visual Studio Code (aka VS Code)](https://code.visualstudio.com/)
- 🔗 [ES7 React Snippets](https://marketplace.visualstudio.com/items?itemName=dsznajder.es7-react-js-snippets)

### 📚 References
- 🔗 [NextAuth.js Official Site](https://next-auth.js.org/)
- 🔗 [Next.js Official Site](https://nextjs.org/)




================================================
FILE: next.config.js
================================================
/** @type {import('next').NextConfig} */
const nextConfig = {
    images: {
        remotePatterns: [
            {
                protocol: 'https',
                hostname: 'avatars.githubusercontent.com',
                port: '',
                pathname: '/u/**',
            },
        ],
    },
}

module.exports = nextConfig


================================================
FILE: package.json
================================================
{
  "name": "next-auth-tut",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "@types/node": "20.3.2",
    "@types/react": "18.2.14",
    "@types/react-dom": "18.2.6",
    "autoprefixer": "10.4.14",
    "eslint": "8.43.0",
    "eslint-config-next": "13.4.7",
    "next": "13.4.7",
    "next-auth": "^4.22.1",
    "postcss": "8.4.24",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "tailwindcss": "3.3.2",
    "typescript": "5.1.6"
  }
}


================================================
FILE: postcss.config.js
================================================
module.exports = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  },
}


================================================
FILE: src/app/api/auth/[...nextauth]/options.ts
================================================
import type { NextAuthOptions } from 'next-auth'
import GitHubProvider from 'next-auth/providers/github'
import CredentialsProvider from 'next-auth/providers/credentials'

export const options: NextAuthOptions = {
    providers: [
        GitHubProvider({
            clientId: process.env.GITHUB_ID as string,
            clientSecret: process.env.GITHUB_SECRET as string,
        }),
        CredentialsProvider({
            name: "Credentials",
            credentials: {
                username: {
                    label: "Username:",
                    type: "text",
                    placeholder: "your-cool-username"
                },
                password: {
                    label: "Password:",
                    type: "password",
                    placeholder: "your-awesome-password"
                }
            },
            async authorize(credentials) {
                // This is where you need to retrieve user data 
                // to verify with credentials
                // Docs: https://next-auth.js.org/configuration/providers/credentials
                const user = { id: "42", name: "Dave", password: "nextauth" }

                if (credentials?.username === user.name && credentials?.password === user.password) {
                    return user
                } else {
                    return null
                }
            }
        })
    ],
}

================================================
FILE: src/app/api/auth/[...nextauth]/route.ts
================================================
import NextAuth from 'next-auth'
import { options } from './options'

const handler = NextAuth(options)

export { handler as GET, handler as POST }

================================================
FILE: src/app/client/page.tsx
================================================
'use client'
// Remember you must use an AuthProvider for 
// client components to useSession
import { useSession } from 'next-auth/react'
import { redirect } from 'next/navigation'
import UserCard from '../components/UserCard'

export default function ClientPage() {
    const { data: session } = useSession({
        required: true,
        onUnauthenticated() {
            redirect('/api/auth/signin?callbackUrl=/client')
        }
    })

    return (
        <section className="flex flex-col gap-6">
            <UserCard user={session?.user} pagetype={"Client"} />
        </section>
    )
}

================================================
FILE: src/app/components/Navbar.tsx
================================================
import Link from "next/link"

export default function Navbar() {
    return (
        <nav className="bg-blue-800 p-4">
            <ul className="flex justify-evenly text-2xl font-bold">
                <li><Link href="/">Home</Link></li>
                <li><Link href="/api/auth/signin">Sign In</Link></li>
                <li><Link href="/api/auth/signout">Sign Out</Link></li>
                <li><Link href="/server">Server</Link></li>
                <li><Link href="/client">Client</Link></li>
                <li><Link href="/extra">Extra</Link></li>
            </ul>
        </nav>
    )
}



================================================
FILE: src/app/components/UserCard.tsx
================================================
import Image from "next/image"

type User = {
    name?: string | null | undefined;
    email?: string | null | undefined;
    image?: string | null | undefined;
} | undefined

type Props = {
    user: User,
    pagetype: string,
}

export default function Card({ user, pagetype }: Props) {

    //console.log(user)

    const greeting = user?.name ? (
        <div className="flex flex-col items-center p-6 bg-white rounded-lg font-bold text-5xl text-black">
            Hello {user?.name}!
        </div>
    ) : null

    // const emailDisplay = user?.email ? (
    //     <div className="flex flex-col items-center p-6 bg-white rounded-lg font-bold text-5xl text-black">
    //         {user?.email}
    //     </div>
    // ) : null

    const userImage = user?.image ? (
        <Image
            className="border-4 border-black dark:border-slate-500 drop-shadow-xl shadow-black rounded-full mx-auto mt-8"
            src={user?.image}
            width={200}
            height={200}
            alt={user?.name ?? "Profile Pic"}
            priority={true}
        />
    ) : null

    return (
        <section className="flex flex-col gap-4">
            {greeting}
            {/* {emailDisplay} */}
            {userImage}
            <p className="text-2xl text-center">{pagetype} Page!</p>
        </section>
    )
}

================================================
FILE: src/app/context/AuthProvider.tsx
================================================
'use client'

import { SessionProvider } from 'next-auth/react'

export default function AuthProvider({ children }: {
    children: React.ReactNode
}) {
    return (
        <SessionProvider>
            {children}
        </SessionProvider>
    )
}


================================================
FILE: src/app/extra/page.tsx
================================================
export default async function ExtraPage() {

    return <h1 className="text-5xl">Extra Page!</h1>

}

================================================
FILE: src/app/globals.css
================================================
@tailwind base;
@tailwind components;
@tailwind utilities;

:root {
  --foreground-rgb: 0, 0, 0;
  --background-start-rgb: 214, 219, 220;
  --background-end-rgb: 255, 255, 255;
}

@media (prefers-color-scheme: dark) {
  :root {
    --foreground-rgb: 255, 255, 255;
    --background-start-rgb: 0, 0, 0;
    --background-end-rgb: 0, 0, 0;
  }
}

body {
  color: rgb(var(--foreground-rgb));
  background: linear-gradient(
      to bottom,
      transparent,
      rgb(var(--background-end-rgb))
    )
    rgb(var(--background-start-rgb));
}


================================================
FILE: src/app/layout.tsx
================================================
import './globals.css'
import { Inter } from 'next/font/google'
import Navbar from './components/Navbar'
import AuthProvider from './context/AuthProvider'

const inter = Inter({ subsets: ['latin'] })

export const metadata = {
  title: 'NextAuth Tutorial',
  description: 'Learn NextAuth.js by Dave Gray',
}

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      <body className={inter.className}>
        <AuthProvider>
          <Navbar />
          <main className="flex justify-center items-start p-6 min-h-screen">
            {children}
          </main>
        </AuthProvider>
      </body>
    </html>
  )
}


================================================
FILE: src/app/page.tsx
================================================
import { options } from "./api/auth/[...nextauth]/options"
import { getServerSession } from "next-auth/next"
import UserCard from "./components/UserCard"

export default async function Home() {
  const session = await getServerSession(options)

  return (
    <>
      {session ? (
        <UserCard user={session?.user} pagetype={"Home"} />
      ) : (
        <h1 className="text-5xl">You Shall Not Pass!</h1>
      )}
    </>
  )
}


================================================
FILE: src/app/server/page.tsx
================================================
import { options } from "../api/auth/[...nextauth]/options"
import { getServerSession } from "next-auth/next"
import UserCard from "../components/UserCard"
import { redirect } from "next/navigation"

export default async function ServerPage() {
    const session = await getServerSession(options)

    if (!session) {
        redirect('/api/auth/signin?callbackUrl=/server')
    }

    return (
        <section className="flex flex-col gap-6">
            <UserCard user={session?.user} pagetype={"Server"} />
        </section>
    )

}


================================================
FILE: src/middleware.ts
================================================
// Without a defined matcher, this one line applies next-auth 
// to the entire project
export { default } from "next-auth/middleware"

// Applies next-auth only to matching routes - can be regex
// Ref: https://nextjs.org/docs/app/building-your-application/routing/middleware#matcher
export const config = { matcher: ["/extra", "/dashboard"] }

================================================
FILE: tailwind.config.js
================================================
/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    './src/pages/**/*.{js,ts,jsx,tsx,mdx}',
    './src/components/**/*.{js,ts,jsx,tsx,mdx}',
    './src/app/**/*.{js,ts,jsx,tsx,mdx}',
  ],
  theme: {
    extend: {
      backgroundImage: {
        'gradient-radial': 'radial-gradient(var(--tw-gradient-stops))',
        'gradient-conic':
          'conic-gradient(from 180deg at 50% 50%, var(--tw-gradient-stops))',
      },
    },
  },
  plugins: [],
}


================================================
FILE: tsconfig.json
================================================
{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "plugins": [
      {
        "name": "next"
      }
    ],
    "paths": {
      "@/*": ["./src/*"]
    }
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
  "exclude": ["node_modules"]
}
Download .txt
gitextract_gzu13coo/

├── .eslintrc.json
├── .gitignore
├── README.md
├── next.config.js
├── package.json
├── postcss.config.js
├── src/
│   ├── app/
│   │   ├── api/
│   │   │   └── auth/
│   │   │       └── [...nextauth]/
│   │   │           ├── options.ts
│   │   │           └── route.ts
│   │   ├── client/
│   │   │   └── page.tsx
│   │   ├── components/
│   │   │   ├── Navbar.tsx
│   │   │   └── UserCard.tsx
│   │   ├── context/
│   │   │   └── AuthProvider.tsx
│   │   ├── extra/
│   │   │   └── page.tsx
│   │   ├── globals.css
│   │   ├── layout.tsx
│   │   ├── page.tsx
│   │   └── server/
│   │       └── page.tsx
│   └── middleware.ts
├── tailwind.config.js
└── tsconfig.json
Download .txt
SYMBOL INDEX (11 symbols across 9 files)

FILE: src/app/api/auth/[...nextauth]/options.ts
  method authorize (line 25) | async authorize(credentials) {

FILE: src/app/client/page.tsx
  function ClientPage (line 8) | function ClientPage() {

FILE: src/app/components/Navbar.tsx
  function Navbar (line 3) | function Navbar() {

FILE: src/app/components/UserCard.tsx
  type User (line 3) | type User = {
  type Props (line 9) | type Props = {
  function Card (line 14) | function Card({ user, pagetype }: Props) {

FILE: src/app/context/AuthProvider.tsx
  function AuthProvider (line 5) | function AuthProvider({ children }: {

FILE: src/app/extra/page.tsx
  function ExtraPage (line 1) | async function ExtraPage() {

FILE: src/app/layout.tsx
  function RootLayout (line 13) | function RootLayout({

FILE: src/app/page.tsx
  function Home (line 5) | async function Home() {

FILE: src/app/server/page.tsx
  function ServerPage (line 6) | async function ServerPage() {
Condensed preview — 20 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (12K chars).
[
  {
    "path": ".eslintrc.json",
    "chars": 40,
    "preview": "{\n  \"extends\": \"next/core-web-vitals\"\n}\n"
  },
  {
    "path": ".gitignore",
    "chars": 368,
    "preview": "# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.\n\n# dependencies\n/node_modules\n/.pn"
  },
  {
    "path": "README.md",
    "chars": 1276,
    "preview": "# \"NextAuth.js Login Authentication\"\n\n## With Next.js App Router\n\n---\n\n### Author Links\n\n👋 Hello, I'm Dave Gray.\n\n👉 [My "
  },
  {
    "path": "next.config.js",
    "chars": 335,
    "preview": "/** @type {import('next').NextConfig} */\nconst nextConfig = {\n    images: {\n        remotePatterns: [\n            {\n    "
  },
  {
    "path": "package.json",
    "chars": 581,
    "preview": "{\n  \"name\": \"next-auth-tut\",\n  \"version\": \"0.1.0\",\n  \"private\": true,\n  \"scripts\": {\n    \"dev\": \"next dev\",\n    \"build\":"
  },
  {
    "path": "postcss.config.js",
    "chars": 82,
    "preview": "module.exports = {\n  plugins: {\n    tailwindcss: {},\n    autoprefixer: {},\n  },\n}\n"
  },
  {
    "path": "src/app/api/auth/[...nextauth]/options.ts",
    "chars": 1408,
    "preview": "import type { NextAuthOptions } from 'next-auth'\nimport GitHubProvider from 'next-auth/providers/github'\nimport Credenti"
  },
  {
    "path": "src/app/api/auth/[...nextauth]/route.ts",
    "chars": 147,
    "preview": "import NextAuth from 'next-auth'\nimport { options } from './options'\n\nconst handler = NextAuth(options)\n\nexport { handle"
  },
  {
    "path": "src/app/client/page.tsx",
    "chars": 599,
    "preview": "'use client'\n// Remember you must use an AuthProvider for \n// client components to useSession\nimport { useSession } from"
  },
  {
    "path": "src/app/components/Navbar.tsx",
    "chars": 602,
    "preview": "import Link from \"next/link\"\n\nexport default function Navbar() {\n    return (\n        <nav className=\"bg-blue-800 p-4\">\n"
  },
  {
    "path": "src/app/components/UserCard.tsx",
    "chars": 1332,
    "preview": "import Image from \"next/image\"\n\ntype User = {\n    name?: string | null | undefined;\n    email?: string | null | undefine"
  },
  {
    "path": "src/app/context/AuthProvider.tsx",
    "chars": 250,
    "preview": "'use client'\n\nimport { SessionProvider } from 'next-auth/react'\n\nexport default function AuthProvider({ children }: {\n  "
  },
  {
    "path": "src/app/extra/page.tsx",
    "chars": 100,
    "preview": "export default async function ExtraPage() {\n\n    return <h1 className=\"text-5xl\">Extra Page!</h1>\n\n}"
  },
  {
    "path": "src/app/globals.css",
    "chars": 538,
    "preview": "@tailwind base;\n@tailwind components;\n@tailwind utilities;\n\n:root {\n  --foreground-rgb: 0, 0, 0;\n  --background-start-rg"
  },
  {
    "path": "src/app/layout.tsx",
    "chars": 688,
    "preview": "import './globals.css'\nimport { Inter } from 'next/font/google'\nimport Navbar from './components/Navbar'\nimport AuthProv"
  },
  {
    "path": "src/app/page.tsx",
    "chars": 435,
    "preview": "import { options } from \"./api/auth/[...nextauth]/options\"\nimport { getServerSession } from \"next-auth/next\"\nimport User"
  },
  {
    "path": "src/app/server/page.tsx",
    "chars": 539,
    "preview": "import { options } from \"../api/auth/[...nextauth]/options\"\nimport { getServerSession } from \"next-auth/next\"\nimport Use"
  },
  {
    "path": "src/middleware.ts",
    "chars": 344,
    "preview": "// Without a defined matcher, this one line applies next-auth \n// to the entire project\nexport { default } from \"next-au"
  },
  {
    "path": "tailwind.config.js",
    "chars": 480,
    "preview": "/** @type {import('tailwindcss').Config} */\nmodule.exports = {\n  content: [\n    './src/pages/**/*.{js,ts,jsx,tsx,mdx}',\n"
  },
  {
    "path": "tsconfig.json",
    "chars": 642,
    "preview": "{\n  \"compilerOptions\": {\n    \"target\": \"es5\",\n    \"lib\": [\"dom\", \"dom.iterable\", \"esnext\"],\n    \"allowJs\": true,\n    \"sk"
  }
]

About this extraction

This page contains the full source code of the gitdagray/next-auth-intro GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 20 files (10.5 KB), approximately 3.4k tokens, and a symbol index with 11 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!