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"임을 알려줌

+ Recent posts