Next.js에 Auth0 적용하기
Next.js(App Router) 프로젝트에 Auth0 인증을 적용하는 방법을 안내합니다.
1. Auth0 계정 및 Application 설정
회원가입
- auth0.com에 접속하여 Sign Up 클릭
- 계정 생성 후 Tenant 이름 설정 (예:
nanumspace)
Application 생성
- Auth0 Dashboard → Applications → Create Application
- 이름 입력 (예:
nanumspace-web) - 타입: Regular Web Applications 선택
- Create 클릭
Callback URL 설정
Application의 Settings 탭에서 아래 항목을 설정합니다.
| 항목 | 값 |
|---|---|
| Allowed Callback URLs | http://localhost:3000/api/auth/callback |
| Allowed Logout URLs | http://localhost:3000 |
| Allowed Web Origins | http://localhost:3000 |
배포 시
프로덕션 배포 시 http://localhost:3000 대신 실제 도메인을 추가해야 합니다. 쉼표로 구분하여 여러 URL을 등록할 수 있습니다.
2. 패키지 설치
npm install @auth0/nextjs-auth0
3. 환경 변수 설정
프로젝트 루트에 .env.local 파일을 생성합니다.
.env.local
AUTH0_SECRET='임의의-긴-랜덤-문자열'
AUTH0_BASE_URL='http://localhost:3000'
AUTH0_ISSUER_BASE_URL='https://YOUR_TENANT.auth0.com'
AUTH0_CLIENT_ID='YOUR_CLIENT_ID'
AUTH0_CLIENT_SECRET='YOUR_CLIENT_SECRET'
AUTH0_SECRET— 세션 암호화용 키 (아래 명령어로 생성)AUTH0_ISSUER_BASE_URL— Auth0 Dashboard의 Domain 값AUTH0_CLIENT_ID/AUTH0_CLIENT_SECRET— Application Settings에서 확인
시크릿 키 생성:
openssl rand -hex 32
주의
.env.local은 절대 Git에 커밋하지 마세요. .gitignore에 포함되어 있는지 확인하세요.
4. Auth0 API 라우트 설정
App Router (Next.js 13+)
app/api/auth/[auth0]/route.ts
import { handleAuth } from '@auth0/nextjs-auth0';
export const GET = handleAuth();
이 한 줄로 다음 라우트가 자동 생성됩니다.
| 라우트 | 기능 |
|---|---|
/api/auth/login | 로그인 시작 |
/api/auth/callback | 인증 콜백 처리 |
/api/auth/logout | 로그아웃 |
/api/auth/me | 사용자 정보 조회 |
5. UserProvider 설정
최상위 레이아웃에 UserProvider를 추가합니다.
app/layout.tsx
import { UserProvider } from '@auth0/nextjs-auth0/client';
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="ko">
<body>
<UserProvider>{children}</UserProvider>
</body>
</html>
);
}
6. 로그인/로그아웃 버튼 구현
components/AuthButton.tsx
'use client';
import { useUser } from '@auth0/nextjs-auth0/client';
export default function AuthButton() {
const { user, isLoading } = useUser();
if (isLoading) return <div>로딩 중...</div>;
if (user) {
return (
<div>
<p>{user.name}님 환영합니다</p>
<a href="/api/auth/logout">로그아웃</a>
</div>
);
}
return <a href="/api/auth/login">로그인</a>;
}
7. 페이지 보호하기
클라이언트 컴포넌트에서
'use client';
import { withPageAuthRequired } from '@auth0/nextjs-auth0/client';
function DashboardPage() {
return <div>로그인한 사용자만 볼 수 있습니다</div>;
}
export default withPageAuthRequired(DashboardPage);
서버 컴포넌트에서
app/dashboard/page.tsx
import { getSession } from '@auth0/nextjs-auth0';
import { redirect } from 'next/navigation';
export default async function DashboardPage() {
const session = await getSession();
if (!session) {
redirect('/api/auth/login');
}
return <div>{session.user.name}님의 대시보드</div>;
}
8. API 라우트 보호하기
app/api/protected/route.ts
import { getSession } from '@auth0/nextjs-auth0';
import { NextResponse } from 'next/server';
export async function GET() {
const session = await getSession();
if (!session) {
return NextResponse.json({ error: '인증이 필요합니다' }, { status: 401 });
}
return NextResponse.json({ message: `안녕하세요, ${session.user.name}` });
}
전체 흐름 요약
1. npm install @auth0/nextjs-auth0
2. .env.local에 Auth0 설정값 입력
3. app/api/auth/[auth0]/route.ts 생성
4. layout.tsx에 UserProvider 추가
5. useUser() 또는 getSession()으로 사용자 정보 활용