import { cookies } from "next/headers";
class CookieManager {
private static readonly TOKEN_NAME = "token";
private static readonly COOKIE_OPTIONS = {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "strict" as const,
maxAge: 60 * 60 * 24 * 7, // 7 days
};
private static async getCookieStore() {
return await cookies();
}
static async setAuthToken(token: string) {
const cookieStore = await this.getCookieStore();
cookieStore.set(this.TOKEN_NAME, token, this.COOKIE_OPTIONS);
}
static async getAuthToken() {
const cookieStore = await this.getCookieStore();
return cookieStore.get(this.TOKEN_NAME)?.value;
}
static async removeAuthToken() {
const cookieStore = await this.getCookieStore();
cookieStore.delete(this.TOKEN_NAME);
}
}
export const { setAuthToken, getAuthToken, removeAuthToken } = CookieManager;
1. httpOnly: true
JavaScript를 통해 쿠키에 접근하는 것을 방지
XSS(Cross-Site Scripting) 공격으로부터 보호
오직 HTTP(S) 요청을 통해서만 쿠키 전송 가능
2. secure: process.env.NODE_ENV === "production"
프로덕션 환경에서만 HTTPS를 통해서만 쿠키 전송
개발 환경(NODE_ENV !== "production")에서는 HTTP도 허용
중간자 공격(Man-in-the-Middle) 방지
3. sameSite: "strict" as const
"strict": 같은 도메인의 요청에서만 쿠키 전송
CSRF(Cross-Site Request Forgery) 공격 방지
다른 옵션: "lax", "none"
as const는 TypeScript에게 이 값이 정확히 "strict"임을 알려줌
'개발 > NEXTJS' 카테고리의 다른 글
| "Bearer Token Authentication" 방식에서 쿠키 기반 인증 시스템으로 마이그레이션 (0) | 2025.02.24 |
|---|---|
| nextjs에서 사용자 정보를 swr과 zustand를 사용하여 관리하기 (0) | 2025.02.23 |
| supabase에서 회원 탈퇴 구현하기 (0) | 2025.02.10 |
| 모달창에서 스크롤 방지 (0) | 2025.02.10 |
| error.tsx 사용 (0) | 2025.02.10 |