การผสานรวม NextAuth.js
ตั้งค่า NextAuth.js เพื่อการยืนยันตัวตนที่ง่ายดายด้วยผู้ให้บริการหลากหลายและการเข้าสู่ระบบด้วยข้อมูลรับรอง
การผสานรวม NextAuth.js เป็นบทเรียน Next.js 15 Fullstack Web Apps ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Next.js 15 Fullstack Web Apps และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Next.js 15 Fullstack Web Apps มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
What is NextAuth.js?
Welcome to integrating NextAuth.js! This powerful library simplifies authentication in Next.js applications, making it easy to add login functionality.
NextAuth.js supports various authentication strategies, from social logins (like Google, GitHub) to custom credential-based systems, all with minimal setup.
It handles session management, JWTs, and secure callbacks, abstracting away much of the complexity of building a secure authentication system.
Installing NextAuth.js
First, let's add NextAuth.js to your Next.js project. Open your terminal in your project's root directory and run the following command:
npm install next-authSetting up the Auth API Route
NextAuth.js needs a special API route to handle all authentication requests. For the App Router, create a file at app/api/auth/[...nextauth]/route.js.
This file exports a handler that NextAuth.js uses to process sign-in, sign-out, and session requests. Initially, we'll set it up with no providers.
import NextAuth from "next-auth";
export const authOptions = {
providers: [], // Your authentication providers go here
};
const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };Adding a Google OAuth Provider
Let's integrate Google as an OAuth provider. You'll need to install the specific provider package and then add it to your authOptions.
Make sure you've set up a Google OAuth client ID and secret in the Google Cloud Console.
import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";
// Install: npm install @next-auth/google
export const authOptions = {
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
}),
],
};
const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };Securing Credentials (.env.local)
It's crucial to keep your API keys and secrets secure. Store them in a .env.local file in your project's root directory.
You'll need a NEXTAUTH_SECRET (a long, random string) for signing tokens and encrypting cookies, along with your Google credentials.
GOOGLE_CLIENT_ID=your_google_client_id_here
GOOGLE_CLIENT_SECRET=your_google_client_secret_here
NEXTAUTH_SECRET=a_very_long_and_random_string_for_securityClient Session Provider
To make session data available to your client components, you need to wrap your application with a SessionProvider. For the App Router, create a client component like app/providers.jsx:
"use client";
import { SessionProvider } from "next-auth/react";
export default function AuthProvider({ children }) {
return <SessionProvider>{children}</SessionProvider>;
}Integrating AuthProvider
Now, import and use your custom AuthProvider in your root layout file (app/layout.js). This ensures that all components within your application can access the session context.
import AuthProvider from "./providers"; // Adjust path as needed
export default function RootLayout({ children }) {
return (
<html>
<body>
<AuthProvider>
{children}
</AuthProvider>
</body>
</html>
);
}Accessing Session Data (useSession)
In any client component, you can use the useSession hook from next-auth/react to access the current user's session data.
It provides the session object (if a user is logged in) and a status (e.g., 'loading', 'authenticated', 'unauthenticated').
"use client";
import { useSession } from "next-auth/react";
export default function UserInfo() {
const { data: session, status } = useSession();
if (status === "loading") {
return <p>Loading user info...</p>;
}
if (session) {
return (
<div>
<p>Welcome, {session.user.name}!</p>
<p>Email: {session.user.email}</p>
</div>
);
}
return <p>Please sign in.</p>;
}Authentication UI Actions
To allow users to sign in and out, NextAuth.js provides the signIn and signOut functions. You can import these and use them with buttons or links.
signIn() can take a provider ID (e.g., 'google') to specify the login method.
"use client";
import { useSession, signIn, signOut } from "next-auth/react";
export default function AuthButtons() {
const { data: session } = useSession();
if (session) {
return (
<button onClick={() => signOut()} style={{ padding: '10px' }}>
Sign Out
</button>
);
}
return (
<button onClick={() => signIn("google")} style={{ padding: '10px' }}>
Sign In with Google
</button>
);
}Beyond OAuth: Credentials Provider
While OAuth providers are convenient, NextAuth.js also supports a CredentialsProvider for custom username/password login forms.
This requires you to implement your own authorize function to validate user input against your database, offering full control over the login process.
// ... in your authOptions.providers array
CredentialsProvider({
name: "Credentials",
credentials: {
email: { label: "Email", type: "email" },
password: { label: "Password", type: "password" }
},
async authorize(credentials, req) {
// Here you'd query your database to validate credentials
// If valid, return a user object; otherwise, return null
// Example: const user = await getUserByEmailAndPassword(credentials.email, credentials.password);
// if (user) { return user; } else { return null; }
return null; // Placeholder
}
})NextAuth.js Setup Quiz
You've learned the core steps to integrate NextAuth.js. Let's quickly check your understanding.
Recap: NextAuth.js Integration
Great job! You've learned how to integrate NextAuth.js into your Next.js application:
- Installed the
next-authpackage. - Set up the dynamic API route for authentication (
app/api/auth/[...nextauth]/route.js). - Configured a social OAuth provider like Google.
- Secured credentials using
.env.local. - Wrapped your app with
SessionProviderfor client-side session access. - Used
useSessionto get user data and implementedsignIn/signOutfunctions.
NextAuth.js significantly streamlines the process of adding robust authentication to your Next.js projects!
คำถามที่พบบ่อย
บทเรียน “การผสานรวม NextAuth.js” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การผสานรวม NextAuth.js” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Next.js 15 Fullstack Web Apps ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Next.js 15 Fullstack Web Apps มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การผสานรวม NextAuth.js”
ตั้งค่า NextAuth.js เพื่อการยืนยันตัวตนที่ง่ายดายด้วยผู้ให้บริการหลากหลายและการเข้าสู่ระบบด้วยข้อมูลรับรอง คุณปฏิบัติ Next.js 15 Fullstack Web Apps ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Next.js 15 Fullstack Web Apps หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Next.js 15 Fullstack Web Apps บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน
บทเรียน “การผสานรวม NextAuth.js” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Next.js 15 Fullstack Web Apps นี้ได้ไหม
ได้ บทเรียน Next.js 15 Fullstack Web Apps ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การผสานรวม NextAuth.js
- การจัดการเซสชันและ JWT
- มิดเดิลแวร์และการควบคุมการเข้าถึง
- การควบคุมการเข้าถึงตามบทบาท (RBAC)