User Authentication with Auth.js in Next.js App Router
Table of Contents
Initial Setup
- Install
-
Configure
- NextAuthConfig settings
- Route Handler Setup
- Middleware
- Get Session in Server Side Component
- Get Session in Client Side Component
- Folder structure
Implementing Authentication: Credentials and Google OAuth
- Setting up prisma
- Credentials
-
Add Google OAuth Provider
- Setting Google OAuth application
- Setting Redirect URI
- Setup Environment Variables
- Setup Provider
- Creating Login and Signup page
- Folder Structure
Initial Setup
Install
npm install next-auth@beta
// env.local AUTH_SECRET=GENERATETD_RANDOM_VALUE
Configure
NextAuthConfig settings
// 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.
- Using a built-in OAuth Provider(e.g Github, Google, etc...)
- Using a custom OAuth Provider
- Using Email
- Using Credentials
https://authjs.dev/reference/nextjs#providers
Route Handler Setup
// 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.
Middleware
// 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
Get Session in Server Side Component
// 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> ) }
Get Session in Client Side Component
// 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> ); }
Folder structure
/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
Implementing Authentication: Credentials and Google OAuth
Setting up prisma
// 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
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:
- modules that connect your authentication system to your database or data storage solution.
secret:
- This is a random string used to hash tokens, sign/encrypt cookies, and generate cryptographic keys.
- It's crucial for security and should be kept secret.
- In this case, it's set using an environment variable AUTH_SECRET.
pages:
- This object allows you to customize the URLs for authentication pages.
- In your example, signIn: '/login' means the sign-in page will be at the '/login' route instead of the default '/api/auth/signin'.
session:
- This configures how sessions are handled.
- strategy: "jwt" means JSON Web Tokens will be used for session management instead of database sessions.
callbacks:
- These are functions that are called at various points in the authentication flow, allowing you to customize the process.
jwt callback:
- This runs when a JWT is created or updated.
- In your code, it's adding user information (id, email, name) to the token.
session callback:
- This runs whenever a session is checked.
- Your code is adding the user information from the token to the session object.
Add Google OAuth Provider
Setting Google OAuth application
Create new OAuth Client ID from GCP Console > APIs & Services > Credentials
Once created, save your Client ID and Client Secret for later use.
Setting Redirect URI
When we work in local, set http://localhost:3000/api/auth/callback/google
In production environment, just replace http://localhost:3000 with https://------.
Setup Environment Variables
// env.local AUTH_SECRET=GENERATETD_RANDOM_VALUE
Setup Provider
// 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
Creating Login and Signup page
// 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
Folder Structure
// 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.
