0Pricing
Next.js 15 Fullstack (App Router + Server Actions) · 강의

NextAuth.js 통합

Next.js 애플리케이션에서 쉽고 안전한 인증을 사용할 수 있도록 NextAuth.js를 설정하고 구성합니다.

NextAuth.js 통합은(는) CoddyKit의 무료 Next.js 15 Fullstack (App Router + Server Actions) 강의입니다. 이것은 6개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Next.js 15 Fullstack (App Router + Server Actions) 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Next.js 15 Fullstack (App Router + Server Actions) 강의에는 총 6개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Auth with Next.js 15

Welcome to Integrating NextAuth.js! In modern web applications, user authentication is crucial. It allows users to sign in, proves their identity, and grants them access to personalized content.

Implementing authentication from scratch can be complex and error-prone, involving secure password hashing, session management, and protecting against various attacks.

Introducing NextAuth.js

NextAuth.js (now often referred to as Auth.js) is a complete open-source authentication solution for Next.js applications. It simplifies adding authentication to your project significantly.

  • Easy Setup: Get authentication working quickly with minimal configuration.
  • Multiple Providers: Supports various authentication methods like Google, GitHub, Email, or custom credentials.
  • Secure: Handles many security best practices for you.
  • Flexible: Works seamlessly with both Client and Server Components.

Installation

First, let's install the next-auth package in your Next.js project. Open your terminal in the project root and run:

You'll also need to configure environment variables for security and proper functioning.

npm install next-auth

NextAuth.js Configuration

In Next.js 15 (App Router), NextAuth.js uses a configuration file, typically auth.ts, to define how authentication works. This file exports a configuration object that includes your authentication providers.

You also need to set an environment variable, AUTH_SECRET, which is used to sign and encrypt session tokens. It should be a long, random string.

import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";

export const { handlers, auth, signIn, signOut } = NextAuth({
  providers: [
    CredentialsProvider({
      name: "Credentials",
      credentials: {
        username: { label: "Username", type: "text", placeholder: "jsmith" },
        password: { label: "Password", type: "password" }
      },
      async authorize(credentials, req) {
        // Logic to verify user credentials
        // Return user object if successful, null otherwise
        return null; 
      }
    })
  ],
  pages: {
    signIn: '/auth/signin',
  }
});

Credentials Provider

The Credentials Provider allows users to sign in with a username/email and password. You define the input fields (credentials) and provide an authorize function.

The authorize function is where you'll verify the user's input against your database. For this example, we'll use a simple hardcoded check.

import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";

export const { handlers, auth, signIn, signOut } = NextAuth({
  providers: [
    CredentialsProvider({
      name: "Credentials",
      credentials: {
        username: { label: "Username", type: "text", placeholder: "test" },
        password: { label: "Password", type: "password" }
      },
      async authorize(credentials) {
        if (credentials?.username === "user" && credentials?.password === "pass") {
          return { id: "1", name: "Test User", email: "test@example.com" };
        }
        return null; // Authentication failed
      }
    })
  ],
  pages: {
    signIn: '/auth/signin',
  }
});

Sign-in Page Component

Now, let's create a client component that provides a sign-in form. We'll use the signIn function exported from our auth.ts file (or next-auth/react if preferred for client components).

This component will handle user input and trigger the authentication flow using the Credentials Provider we configured.

// app/auth/signin/page.tsx (Client Component)
'use client';

import { signIn } from "next-auth/react";
import { useState } from "react";

export default function SignInPage() {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    const result = await signIn('credentials', {
      username,
      password,
      redirect: false, // Don't redirect automatically
    });

    if (result?.error) {
      alert(result.error);
    } else {
      window.location.href = '/'; // Redirect on success
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        placeholder="Username (user)"
        value={username}
        onChange={(e) => setUsername(e.target.value)}
      />
      <input
        type="password"
        placeholder="Password (pass)"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
      />
      <button type="submit">Sign In</button>
    </form>
  );
}

Displaying Session Data

Once a user is signed in, you can access their session information. In Server Components, you can directly use the auth() function from auth.ts to get the session data.

This is great for rendering UI based on the logged-in user or fetching user-specific data on the server.

// app/page.tsx (Server Component)
import { auth, signOut } from "@/auth"; // Adjust path if needed

export default async function HomePage() {
  const session = await auth();

  return (
    <div>
      <h1>Welcome!</h1>
      {session?.user ? (
        <div>
          <p>Signed in as {session.user.name || session.user.email}</p>
          {/* SignOut button would be in a Client Component */}
        </div>
      ) : (
        <p>Not signed in. <a href="/auth/signin">Sign In</a></p>
      )}
    </div>
  );
}

Implementing Sign Out

Allowing users to sign out is just as important as signing in. You can use the signOut function from next-auth/react in a Client Component.

When called, signOut clears the user's session and typically redirects them to a specified page (like the homepage or a sign-in page).

// app/components/SignOutButton.tsx (Client Component)
'use client';

import { signOut } from "next-auth/react";

export default function SignOutButton() {
  return (
    <button onClick={() => signOut({ callbackUrl: '/' })}> 
      Sign Out
    </button>
  );
}

NextAuth.js Options

NextAuth.js offers many configuration options to customize behavior. In your auth.ts, you can define:

  • pages: Custom URLs for sign-in, sign-out, error pages.
  • callbacks: Functions to control what happens when a user signs in, updates their session, or creates a JWT.
  • session: Configure session storage (JWT or database).
  • secret: The AUTH_SECRET environment variable.

These options provide powerful control over the authentication flow and user experience.

Quick Check

Which file is primarily used to configure NextAuth.js providers and callbacks in a Next.js 15 App Router project?

Recap & Next Steps

You've successfully learned the basics of integrating NextAuth.js into your Next.js 15 application!

  • We installed NextAuth.js.
  • Configured auth.ts with a Credentials Provider.
  • Created client components for sign-in and sign-out.
  • Accessed session data in server components.

In the next lesson, we'll explore how to protect routes and data based on user authentication status using Next.js middleware and server-side checks.

자주 묻는 질문

“NextAuth.js 통합” 강의는 무료인가요?

네 — “NextAuth.js 통합” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Next.js 15 Fullstack (App Router + Server Actions) 강의 전체를 잠금 해제할 수 있습니다. Next.js 15 Fullstack (App Router + Server Actions) 강의에는 총 6개의 강의가 포함되어 있습니다.

“NextAuth.js 통합”에서 뭘 배우나요?

Next.js 애플리케이션에서 쉽고 안전한 인증을 사용할 수 있도록 NextAuth.js를 설정하고 구성합니다. 브라우저에서 직접 실행하는 실습 코드로 Next.js 15 Fullstack (App Router + Server Actions)을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Next.js 15 Fullstack (App Router + Server Actions)을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Next.js 15 Fullstack (App Router + Server Actions)은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 6개 중 1번째 강의입니다.

“NextAuth.js 통합” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Next.js 15 Fullstack (App Router + Server Actions) 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Next.js 15 Fullstack (App Router + Server Actions) 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. NextAuth.js 통합
  2. JWT 전략 구현
  3. 경로 및 데이터 보호
  4. 가드와 역할
  5. 사용자 지정 인증 전략
  6. Passport.js 통합
← Next.js 15 Fullstack (App Router + Server Actions)(으)로 돌아가기