본문으로 건너뛰기

인증

딸깍문서 API는 NextAuth.js 세션 기반 인증을 사용합니다.

인증 방식

세션 기반 인증

모든 API 요청은 유효한 세션이 필요합니다.

import { getServerSession } from "next-auth";
import { authConfig } from "@/server/auth/config";

const session = await getServerSession(authConfig);

if (!session?.user) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}

OAuth 프로바이더

Google OAuth

import GoogleProvider from "next-auth/providers/google";

export const authOptions = {
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID!,
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
}),
],
};

세션 정보

interface Session {
user: {
id: string;
email: string;
name: string;
image?: string;
};
}

클라이언트 사용

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

function Component() {
const { data: session, status } = useSession();

if (status === "loading") return <div>Loading...</div>;
if (!session) return <div>Please sign in</div>;

return <div>Hello {session.user.name}</div>;
}

API 라우트 보호

export async function GET(req: NextRequest) {
const session = await getServerSession(authConfig);

if (!session?.user) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}

// 인증된 사용자만 접근 가능
return NextResponse.json({ data: "protected data" });
}