C.W.K.
Stream
Lesson 04 of 09 · published

Auth.js v5 (NextAuth)

~22 min · Auth.js, OAuth, session

Level 0Curious
0 XP0/68 lessons0/11 achievements
0/120 XP to next level120 XP to go0% complete

auth() 가 어디서든 작동

Auth.js v5 (옛 NextAuth.js) 가 Server Component, Server Action, Route Handler, proxy 에서 도는 단일 auth() helper ship. Mental model: "session 있어?" — 같은 답, 같은 call site, 어디서 묻든.

Setup

next-auth@beta install, provider 설정, handlers + auth export. handlersapp/api/auth/[...nextauth]/route.ts 에서 Route Handler 로 wire.

어디서 auth() 부를지

위치Pattern
Server Componentconst session = await auth();
Server Actionsame
Route Handlersame
ProxyExport wrap: export const proxy = auth(req => { … });

Code

auth.ts — single config file·ts
// auth.ts
import NextAuth from 'next-auth';
import GitHub from 'next-auth/providers/github';
import Google from 'next-auth/providers/google';

export const { handlers, auth, signIn, signOut } = NextAuth({
  providers: [
    GitHub({ clientId: process.env.GITHUB_ID!, clientSecret: process.env.GITHUB_SECRET! }),
    Google({ clientId: process.env.GOOGLE_ID!, clientSecret: process.env.GOOGLE_SECRET! }),
  ],
});
Handler wire 후 어디든 auth() 호출·ts
// app/api/auth/[...nextauth]/route.ts
export { GET, POST } from '@/auth';

// Server Component 안:
import { auth } from '@/auth';
export default async function Page() {
  const session = await auth();
  return session ? <p>Welcome {session.user?.name}</p> : <SignInButton />;
}

// Server Action 안:
export async function createPost() {
  'use server';
  const session = await auth();
  if (!session) throw new Error('Unauthorized');
  // …
}

// proxy.ts 안:
import { auth } from '@/auth';
import { NextResponse } from 'next/server';

export const proxy = auth((req) => {
  if (!req.auth && req.nextUrl.pathname.startsWith('/app')) {
    return NextResponse.redirect(new URL('/login', req.url));
  }
});

External links

Exercise

OAuth provider 한 개로 Auth.js v5 설정. Server Component, Server Action, proxy 에 auth() call 추가. 같은 session 이 셋 다에서 visible 한지 확인.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.