Auth0: Secure access for everyone. But not just anyone.
Rapidly integrate authentication and authorization for web, mobile, and legacy applications so you can focus on your core business.
auth0.com
Pokemon API를 활용한 포켓몬 사이트를 구현하면서 간단한 로그인 기능도 추가하기 위해 Auth0를 사용했습니다.
이번 글에서는 Auth0를 설정하고 Next.js 프로젝트에 통합하는 과정을 정리해보겠습니다.
Auth0 설정하기
- 애플리케이션 유형 선택 Next.js를 사용하기 때문에 Single Page Web Applications를 선택했습니다.
- 애플리케이션 추가 새로운 애플리케이션을 생성합니다. 저는 "Pokemon"이라는 이름으로 어플리케이션을 만들었습니다.
- Allowed Callback URLs 설정 Auth0 대시보드에서 Settings로 이동한 후, Allowed Callback URLs에 아래의 값을 추가합니다.이 URL은 Auth0가 인증 후 리디렉션할 경로를 지정합니다.
- http://localhost:3000/api/auth/callback
Next.js 프로젝트에 Auth0 통합하기
1. Auth0 관련 패키지 설치
Auth0를 Next.js에 통합하려면 다음 패키지를 설치합니다:
npm install @auth0/nextjs-auth0
2. 환경 변수 설정
.env.local 파일에 Auth0 설정 값을 추가합니다:
AUTH0_SECRET='use [openssl rand -hex 32] to generate a 32 bytes value'
AUTH0_BASE_URL='http://localhost:3000'
AUTH0_ISSUER_BASE_URL='https://YOUR_DOMAIN.auth0.com'
AUTH0_CLIENT_ID='YOUR_CLIENT_ID'
AUTH0_CLIENT_SECRET='YOUR_CLIENT_SECRET'
- AUTH0_SECRET: 32바이트 길이의 랜덤 문자열을 생성하려면 터미널에서 다음 명령어를 실행합니다:
openssl rand -hex 32
- 나머지 값은 Auth0 애플리케이션 설정에서 복사하여 사용합니다.
3. API 라우트 추가
app/api/auth/[auth0]/route.ts 파일을 생성하고 다음과 같이 작성합니다:
import { handleAuth } from '@auth0/nextjs-auth0';
export const GET = handleAuth();
4. 레이아웃 설정
app/layout.tsx 파일에서 Auth0의 UserProvider로 애플리케이션을 감쌉니다.
import { UserProvider } from '@auth0/nextjs-auth0/client';
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<UserProvider>
<body>{children}</body>
</UserProvider>
</html>
);
}
이미지 호스트 문제 해결하기
Next.js에서 next/image를 사용할 때 외부 호스트의 이미지를 로드하려면 next.config.js 파일에 해당 호스트를 추가해야 합니다. 다음과 같이 설정합니다.
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
images: {
domains: ['lh3.googleusercontent.com'],
}
/* config options here */
};
export default nextConfig;
로그인 상태에 따른 UI 변경
클라이언트 컴포넌트에서는 Auth0의 useUser 훅을, 서버 컴포넌트에서는 getSession을 사용하여 로그인 상태를 확인할 수 있습니다.
이를 기반으로 로그인 여부에 따라 헤더 UI를 다르게 표시할 수 있습니다.
'use client';
import { useUser } from '@auth0/nextjs-auth0/client';
export default function Header() {
const { user, isLoading } = useUser();
console.log(user);
return <header></header>;
}
import { getSession } from '@auth0/nextjs-auth0';
export default async function Header() {
const session = await getSession();
const user = session?.user;
return <header></header>;
}
현재 Next.js가 15버전인 경우, getSession을 사용하면 다음과 같은 에러가 발생합니다.
Route "/api/auth/[auth0]" used params.auth0. params should be awaited before using its properties
이는 Auth0의 현재 버전이 Next.js 15를 완전히 지원하지 않아서 발생한 문제로 추측됩니다.
현재는 Next.js를 14버전으로 다운그레이드하면 오류가 사라집니다.
'Next.js > Pokemon' 카테고리의 다른 글
Zustand로 상태 관리, 포켓몬 검색 기능 구현하기 (0) | 2025.01.02 |
---|---|
MongoDB와 Prisma를 활용한 북마크/좋아요 기능 구현 (0) | 2025.01.01 |
PokeAPI와 페이지네이션 기능 구현하기 (0) | 2024.12.30 |
Next.js 15.1.2 -> 14.2.21로 다운그레이드 (0) | 2024.12.27 |