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

사용자 지정 인증 전략

기존 라이브러리로 충족하기 어려운 특정 프로젝트 요구 사항에 맞춰 사용자 지정 인증 전략을 개발하고 통합합니다.

레슨 5/611개 단계

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

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

Why Custom Authentication?

While libraries like NextAuth.js are powerful, sometimes your project needs a unique authentication flow. Custom strategies give you full control over every detail.

  • Handle specific integration requirements.
  • Implement unique authentication flows (e.g., magic links).
  • Gain a deeper understanding of core auth concepts.

This lesson explores building authentication from the ground up using Next.js 15 features.

Core Concepts: Sessions & Cookies

Authentication often relies on sessions to maintain a user's logged-in state across multiple requests. To manage sessions in web applications, we primarily use HTTP cookies.

  • Cookies are small data pieces sent by a server to a browser.
  • The browser stores them and sends them back with subsequent requests.
  • They are crucial for remembering user login status.

Building a Login Form (UI)

Our custom authentication starts with a simple login form. This form captures user credentials (like username and password) and submits them to a Next.js Server Action. Each input needs a name attribute to be accessible in the action.

export default function LoginPage() {
  return (
    <form>
      <h2>Login</h2>
      <label htmlFor="username">Username:</label>
      <input id="username" name="username" type="text" required />

      <label htmlFor="password">Password:</label>
      <input id="password" name="password" type="password" required />

      <button type="submit">Log In</button>
    </form>
  );
}

Server Action for Login

When the login form is submitted, a Next.js Server Action intercepts the request. This action runs entirely on the server and is responsible for:

  • Validating the submitted username and password.
  • If valid, creating a session (e.g., generating a unique session ID).
  • Setting a secure HTTP-only cookie in the user's browser.
  • Redirecting the user to a protected page.

Code: Login Server Action

This runnable example simulates a Server Action for login. We mock Next.js's cookies() and redirect() to demonstrate how credentials are checked and a session cookie is set.

'use server';

// Mock Next.js APIs for runnable example
const mockCookies = {
  _store: {},
  set: (n, v, o) => {
    mockCookies._store[n] = { v, o };
    console.log(`[MOCK] Cookie: ${n}=${v}`);
  },
  get: (n) => mockCookies._store[n] ? { value: mockCookies._store[n].v } : undefined,
  delete: (n) => {
    delete mockCookies._store[n];
    console.log(`[MOCK] Deleted: ${n}`);
  }
};
const mockRedirect = (path) => {
  console.log(`[MOCK] Redirect to: ${path}`);
  throw new Error(`MOCK_REDIRECT:${path}`);
};

// Actual Server Action logic
export async function login(formData) {
  const username = formData.get('username');
  const password = formData.get('password');
  const users = {'testuser': 'password123'}; // Mock DB

  if (users[username] === password) {
    mockCookies.set('session', 'some_token', { httpOnly: true, maxAge: 3600 });
    mockRedirect('/dashboard');
  } else {
    console.error('Login failed: Invalid credentials');
  }
}

// Main entry point for runnable example
async function main() {
  console.log("--- Test Login Success ---");
  const successForm = new Map([
    ['username', 'testuser'],
    ['password', 'password123']
  ]);
  try { await login(successForm); }
  catch (e) { console.log(e.message); }

  console.log("\n--- Test Login Fail ---");
  const failForm = new Map([
    ['username', 'wrong'],
    ['password', 'pass']
  ]);
  try { await login(failForm); }
  catch (e) { console.log(e.message); }
  console.log("Final cookies:", mockCookies._store);
}
main();

Protecting Routes with Middleware

After a user logs in, we need to ensure they can't access restricted pages without a valid session. Next.js middleware is perfect for this, running before a request is completed.

  • Middleware intercepts requests to certain paths.
  • It checks for the presence and validity of the session cookie.
  • If no valid session, it redirects the user to the login page.

Code: Authentication Middleware

This middleware.js file demonstrates how to protect the /dashboard route by checking for our custom 'session' cookie. Middleware is a Next.js-specific feature and not runnable in a generic JavaScript environment.

// middleware.js
import { NextResponse } from 'next/server';

export function middleware(request) {
  const sessionCookie = request.cookies.get('session');
  const pathname = request.nextUrl.pathname;

  // Define protected routes
  const protectedRoutes = ['/dashboard'];

  if (protectedRoutes.includes(pathname) && !sessionCookie) {
    // Redirect to login if no session
    const loginUrl = new URL('/login', request.url);
    return NextResponse.redirect(loginUrl);
  }

  return NextResponse.next(); // Allow request to proceed
}

// Configure matcher to run middleware on specific paths
export const config = {
  matcher: ['/((?!api|_next/static|_next/image|favicon.ico|login).*)'],
};

Logout Mechanism

Providing a way for users to log out securely is crucial. A logout Server Action simply needs to delete the session cookie from the user's browser, effectively ending their session.

Code: Logout Server Action

This runnable example shows a Server Action that deletes the 'session' cookie and redirects the user to the login page, simulating a logout.

'use server';

// Mock Next.js APIs for runnable example
const mockCookies = {
  _store: { 'session': { v: 'active_token' } }, // Simulate active session
  set: (n, v, o) => {
    mockCookies._store[n] = { v, o };
    console.log(`[MOCK] Cookie: ${n}=${v}`);
  },
  get: (n) => mockCookies._store[n] ? { value: mockCookies._store[n].v } : undefined,
  delete: (n) => {
    delete mockCookies._store[n];
    console.log(`[MOCK] Deleted: ${n}`);
  }
};
const mockRedirect = (path) => {
  console.log(`[MOCK] Redirect to: ${path}`);
  throw new Error(`MOCK_REDIRECT:${path}`);
};

// Actual Server Action logic
export async function logout() {
  mockCookies.delete('session');
  mockRedirect('/login');
}

// Main entry point for runnable example
async function main() {
  console.log("--- Before Logout ---");
  console.log("Initial cookies:", mockCookies._store);

  console.log("\n--- Attempting Logout ---");
  try { await logout(); }
  catch (e) { console.log(e.message); }
  console.log("Final cookies:", mockCookies._store);
}
main();

Check Your Understanding

Let's test what you've learned about custom authentication in Next.js.

Recap: Custom Auth Strategies

You've learned how to build a custom authentication strategy in Next.js 15, leveraging powerful server-side features for full control.

  • Understood session management with secure HTTP-only cookies.
  • Implemented login and logout functionality using Next.js Server Actions.
  • Secured application routes using Next.js middleware.

Remember to always prioritize security (encryption, HTTPS, secure cookies) when building custom authentication.

무료로 시작

AI 튜터와 함께 TypeScript을(를) 배우세요 — 무료

브라우저에서 실제 코드를 작성하고 실행하며, 24/7 AI 튜터로부터 즉각적인 도움을 받고, 웹이나 앱에서 중단한 부분부터 계속 학습하세요.

코스
22
레슨
88

자주 묻는 질문

“사용자 지정 인증 전략” 강의는 무료인가요?

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

“사용자 지정 인증 전략”에서 뭘 배우나요?

기존 라이브러리로 충족하기 어려운 특정 프로젝트 요구 사항에 맞춰 사용자 지정 인증 전략을 개발하고 통합합니다. 브라우저에서 직접 실행하는 실습 코드로 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개 중 5번째 강의입니다.

“사용자 지정 인증 전략” 강의는 얼마나 걸리나요?

대부분의 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)(으)로 돌아가기