Home >Web Front-end >JS Tutorial >User Authentication with Auth.js in Next.js App Router
npm install next-auth@beta
// env.local AUTH_SECRET=GENERATETD_RANDOM_VALUE
// src/auth.ts import NextAuth from "next-auth" export const config = { providers: [], } export const { handlers, signIn, signOut, auth } = NextAuth(config)
It should be put inside of src folder
Providers means in Auth.js are services that can be used to sign in a user. There are four ways a user can be signed in.
https://authjs.dev/reference/nextjs#providers
// src/app/api/auth/[...nextauth]/route.ts import { handlers } from "@/auth" // Referring to the auth.ts we just created export const { GET, POST } = handlers
This file is used for setting route handler with Next.js App Router.
// src/middleware.ts import { auth } from "@/auth" export default auth((req) => { // Add your logic here } export const config = { matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"], // It's default setting }
Write inside the src folder.
If written outside the src folder, middleware will not work.
Middleware is a function that allows you to run code before a request is completed. It is particularly useful for protecting routes and handling authentication across your application.
Matcher is a configuration option for specifying which routes middleware should apply to. It helps optimize performance by running middleware only on necessary routes.
Example matcher: ['/dashboard/:path*'] applies middleware only to dashboard routes.
https://authjs.dev/getting-started/session-management/protecting?framework=express#nextjs-middleware
// src/app/page.tsx import { auth } from "@/auth" import { redirect } from "next/navigation" export default async function page() { const session = await auth() if (!session) { redirect('/login') } return ( <div> <h1>Hello World!</h1> <img src={session.user.image} alt="User Avatar" /> </div> ) }
// src/app/page.tsx "use client" import { useSession } from "next-auth/react" import { useRouter } from "next/navigation" export default async function page() { const { data: session } = useSession() const router = useRouter() if (!session.user) { router.push('/login') } return ( <div> <h1>Hello World!</h1> <img src={session.user.image} alt="User Avatar" /> </div> ) } // src/app/layout.tsx import type { Metadata } from "next"; import "./globals.css"; import { SessionProvider } from "next-auth/react" export const metadata: Metadata = { title: "Create Next App", description: "Generated by create next app", }; export default function RootLayout({ children, }: Readonly<{ children: React.ReactNode; }>) { return ( <html lang="en"> <body> <SessionProvider> {children} </SessionProvider> </body> </html> ); }
/src /app /api /auth [...nextauth] /route.ts // Route Handler layout.tsx page.tsx auth.ts // Provider, Callback, Logic etc middleware.ts // A function before request
// prisma/schema.prisma model User { id String @id @default(cuid()) name String? email String? @unique emailVerified DateTime? image String? password String? accounts Account[] sessions Session[] } model Account { // ... (standard Auth.js Account model) } model Session { // ... (standard Auth.js Session model) } // ... (other necessary models)
// src/lib/prisma.ts import { PrismaClient } from "@prisma/client" const globalForPrisma = globalThis as unknown as { prisma: PrismaClient } export const prisma = globalForPrisma.prisma || new PrismaClient() if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma
Credentials, in the context of authentication, refer to a method of verifying a user's identity using information that the user provides, typically a username (or email) and password.
We can add credentials in src/auth.ts.
npm install next-auth@beta
adapters:
secret:
pages:
session:
callbacks:
jwt callback:
session callback:
Create new OAuth Client ID from GCP Console > APIs & Services > Credentials
Once created, save your Client ID and Client Secret for later use.
When we work in local, set http://localhost:3000/api/auth/callback/google
In production environment, just replace http://localhost:3000 with https://------.
// env.local AUTH_SECRET=GENERATETD_RANDOM_VALUE
// src/auth.ts import NextAuth from "next-auth" export const config = { providers: [], } export const { handlers, signIn, signOut, auth } = NextAuth(config)
https://authjs.dev/getting-started/authentication/oauth
// src/app/api/auth/[...nextauth]/route.ts import { handlers } from "@/auth" // Referring to the auth.ts we just created export const { GET, POST } = handlers
// src/middleware.ts import { auth } from "@/auth" export default auth((req) => { // Add your logic here } export const config = { matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"], // It's default setting }
// src/app/page.tsx import { auth } from "@/auth" import { redirect } from "next/navigation" export default async function page() { const session = await auth() if (!session) { redirect('/login') } return ( <div> <h1>Hello World!</h1> <img src={session.user.image} alt="User Avatar" /> </div> ) }
// src/app/page.tsx "use client" import { useSession } from "next-auth/react" import { useRouter } from "next/navigation" export default async function page() { const { data: session } = useSession() const router = useRouter() if (!session.user) { router.push('/login') } return ( <div> <h1>Hello World!</h1> <img src={session.user.image} alt="User Avatar" /> </div> ) } // src/app/layout.tsx import type { Metadata } from "next"; import "./globals.css"; import { SessionProvider } from "next-auth/react" export const metadata: Metadata = { title: "Create Next App", description: "Generated by create next app", }; export default function RootLayout({ children, }: Readonly<{ children: React.ReactNode; }>) { return ( <html lang="en"> <body> <SessionProvider> {children} </SessionProvider> </body> </html> ); }
/src /app /api /auth [...nextauth] /route.ts // Route Handler layout.tsx page.tsx auth.ts // Provider, Callback, Logic etc middleware.ts // A function before request
// prisma/schema.prisma model User { id String @id @default(cuid()) name String? email String? @unique emailVerified DateTime? image String? password String? accounts Account[] sessions Session[] } model Account { // ... (standard Auth.js Account model) } model Session { // ... (standard Auth.js Session model) } // ... (other necessary models)
The above is the detailed content of User Authentication with Auth.js in Next.js App Router. For more information, please follow other related articles on the PHP Chinese website!