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 id="Hello-World">Hello World!</h1> <img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/173135190484513.jpg?x-oss-process=image/resize,p_40" class="lazy" 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 id="Hello-World">Hello World!</h1> <img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/173135190484513.jpg?x-oss-process=image/resize,p_40" class="lazy" 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) { return ( <sessionprovider> {children} </sessionprovider> ); }
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 id="Hello-World">Hello World!</h1> <img src="%7Bsession.user.image%7D" 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 id="Hello-World">Hello World!</h1> <img src="%7Bsession.user.image%7D" 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) { return ( <sessionprovider> {children} </sessionprovider> ); }
/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!

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr


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

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version
SublimeText3 Linux latest version

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version
Visual web development tools
