Next.js에서 cookies-next로 쿠키 관리하기

2025. 3. 22. 20:31·TypeScript
반응형
# 설치
npm install cookies-next
# 또는
yarn add cookies-next

# next.js 버전이 12.2~14.x 인 경우 
npm install cookies-next@4.3.0 로 설치

Next.js 애플리케이션에서 사용자 상태 관리나 인증 정보 저장을 위해 쿠키는 필수적입니다. cookies-next 라이브러리는 Next.js의 클라이언트와 서버 컴포넌트 모두에서 쿠키를 손쉽게 다룰 수 있게 해주는 유용한 도구입니다. 이 글에서는 cookies-next의 주요 기능과 실제 활용 방법을 살펴보겠습니다.

cookies-next의 주요 기능

cookies-next는 다음과 같은 핵심 기능을 제공합니다:

  1. 쿠키 설정 (setCookie)
  2. 쿠키 가져오기 (getCookie)
  3. 쿠키 삭제 (deleteCookie)
  4. 모든 쿠키 확인 (hasCookie)

이 라이브러리의 가장 큰 장점은 클라이언트 사이드와 서버 사이드 모두에서 동일한 API로 쿠키를 관리할 수 있다는 점입니다.

기본 사용법

쿠키 설정하기

import { setCookie } from 'cookies-next';

// 클라이언트 사이드에서 사용
function handleLogin() {
  // 로그인 로직...
  setCookie('auth-token', 'your-auth-token-value');
  setCookie('user', JSON.stringify({ id: 1, name: 'John' }));
}

// 서버 사이드에서 사용 (API 라우트나 getServerSideProps 내에서)
export async function getServerSideProps({ req, res }) {
  setCookie('visited', 'true', { req, res });

  return {
    props: {}
  };
}

쿠키에 만료일, 경로 등 추가 옵션을 설정할 수 있습니다:

setCookie('preferences', 'dark-mode', { 
  maxAge: 60 * 60 * 24 * 30, // 30일
  path: '/', 
  secure: process.env.NODE_ENV === 'production',
  sameSite: 'strict'
});

쿠키 가져오기

import { getCookie } from 'cookies-next';

// 클라이언트 사이드에서 사용
function ProfilePage() {
  const userCookie = getCookie('user');
  const user = userCookie ? JSON.parse(userCookie) : null;

  if (!user) {
    return <div>로그인이 필요합니다</div>;
  }

  return <div>안녕하세요, {user.name}님!</div>;
}

// 서버 사이드에서 사용
export async function getServerSideProps({ req, res }) {
  const authToken = getCookie('auth-token', { req, res });

  if (!authToken) {
    return {
      redirect: {
        destination: '/login',
        permanent: false,
      },
    };
  }

  return {
    props: {}
  };
}

쿠키 삭제하기

import { deleteCookie } from 'cookies-next';

function handleLogout() {
  deleteCookie('auth-token');
  deleteCookie('user');
  // 로그아웃 후 리다이렉트...
}

// 서버 사이드에서 삭제
export async function getServerSideProps({ req, res }) {
  deleteCookie('temp-data', { req, res });

  return {
    props: {}
  };
}

쿠키 존재 여부 확인하기

import { hasCookie } from 'cookies-next';

function AuthGuard({ children }) {
  const isAuthenticated = hasCookie('auth-token');

  if (!isAuthenticated) {
    return <div>접근 권한이 없습니다</div>;
  }

  return children;
}

App Router와 함께 사용하기

Next.js 13 이상의 App Router에서도 cookies-next를 활용할 수 있습니다.

클라이언트 컴포넌트에서 사용

'use client'

import { setCookie, getCookie } from 'cookies-next';
import { useState } from 'react';

export default function ThemeToggle() {
  const [theme, setTheme] = useState(() => getCookie('theme') || 'light');

  function toggleTheme() {
    const newTheme = theme === 'light' ? 'dark' : 'light';
    setTheme(newTheme);
    setCookie('theme', newTheme);
    document.documentElement.className = newTheme;
  }

  return (
    <button onClick={toggleTheme}>
      현재 테마: {theme}
    </button>
  );
}

서버 컴포넌트에서 사용

서버 컴포넌트에서는 cookies() API를 사용하는 것이 권장되지만, cookies-next도 사용 가능합니다:

// app/dashboard/page.js
import { cookies } from 'next/headers';

export default function Dashboard() {
  const cookieStore = cookies();
  const theme = cookieStore.get('theme')?.value || 'light';

  return (
    <div className={`dashboard ${theme}`}>
      <h1>대시보드</h1>
      {/* 콘텐츠 */}
    </div>
  );
}

실전 활용 예제

사용자 인증 관리

// lib/auth.js
import { setCookie, getCookie, deleteCookie } from 'cookies-next';

const AUTH_TOKEN_KEY = 'auth-token';
const USER_INFO_KEY = 'user-info';

export function login(token, user) {
  // 보안을 위한 쿠키 옵션
  const cookieOptions = {
    maxAge: 60 * 60 * 24 * 7, // 7일
    path: '/',
    secure: process.env.NODE_ENV === 'production',
    sameSite: 'strict',
    httpOnly: true // 클라이언트에서 JavaScript로 접근 불가
  };

  setCookie(AUTH_TOKEN_KEY, token, cookieOptions);
  setCookie(USER_INFO_KEY, JSON.stringify(user), {
    ...cookieOptions,
    httpOnly: false // 클라이언트에서 접근 필요
  });
}

export function logout() {
  deleteCookie(AUTH_TOKEN_KEY);
  deleteCookie(USER_INFO_KEY);
}

export function getUser() {
  const userCookie = getCookie(USER_INFO_KEY);
  return userCookie ? JSON.parse(userCookie) : null;
}

export function isAuthenticated() {
  return !!getCookie(AUTH_TOKEN_KEY);
}

사용자 선호도 저장

// components/LanguageSelector.jsx
'use client'

import { setCookie, getCookie } from 'cookies-next';
import { useEffect, useState } from 'react';

export default function LanguageSelector() {
  const [language, setLanguage] = useState('');

  useEffect(() => {
    // 컴포넌트 마운트 시 쿠키에서 언어 설정 가져오기
    setLanguage(getCookie('language') || 'ko');
  }, []);

  function handleLanguageChange(e) {
    const newLanguage = e.target.value;
    setLanguage(newLanguage);
    setCookie('language', newLanguage, { maxAge: 60 * 60 * 24 * 365 }); // 1년

    // 언어 변경 시 페이지 새로고침
    window.location.reload();
  }

  return (
    <select value={language} onChange={handleLanguageChange}>
      <option value="ko">한국어</option>
      <option value="en">English</option>
      <option value="ja">日本語</option>
    </select>
  );
}

API 요청 시 인증 정보 사용

// lib/api.js
import { getCookie } from 'cookies-next';

const API_URL = process.env.NEXT_PUBLIC_API_URL;

export async function fetchWithAuth(endpoint, options = {}) {
  const token = getCookie('auth-token');

  const headers = {
    'Content-Type': 'application/json',
    ...(token && { 'Authorization': `Bearer ${token}` }),
    ...options.headers
  };

  const response = await fetch(`${API_URL}${endpoint}`, {
    ...options,
    headers
  });

  if (!response.ok) {
    const error = await response.json().catch(() => ({}));
    throw new Error(error.message || '알 수 없는 오류가 발생했습니다');
  }

  return response.json();
}

주의사항 및 모범 사례

1. 보안에 민감한 정보는 항상 httpOnly, secure, sameSite 옵션을 설정

2. 쿠키는 모든 HTTP 요청에 포함되므로, 크기를 4KB 이하로 유지 

3. 목적에 따라 적절한 만료 기간 설정

// 세션 쿠키 (브라우저 닫으면 만료)
setCookie('session-data', data);

// 영구 쿠키
setCookie('preferences', prefs, { maxAge: 60 * 60 * 24 * 365 });

4. 직렬화/역직렬화 

// 저장
setCookie('user', JSON.stringify(user));

// 가져오기
const user = JSON.parse(getCookie('user') || '{}');

5. 필요한 경로에서만 접근 가능하도록 설정

setCookie('admin-token', token, { path: '/admin' });

 

결론

cookies-next 라이브러리는 Next.js 애플리케이션에서 쿠키를 관리하는 간단하고 효과적인 방법을 제공합니다. 클라이언트와 서버 컴포넌트 모두에서 일관된 API를 사용할 수 있어 개발 편의성이 높습니다.

사용자 인증, 선호도 저장, 세션 관리 등 다양한 시나리오에서 활용할 수 있으며, 적절한 보안 설정과 함께 사용한다면 안전하고 효율적인 쿠키 기반 기능을 구현할 수 있습니다.

Next.js의 새로운 App Router와 함께 사용할 때는 서버 컴포넌트에서는 Next.js 내장 cookies() API를, 클라이언트 컴포넌트에서는 cookies-next를 사용하는 하이브리드 접근 방식도 고려해볼 수 있습니다.

저작자표시 비영리 변경금지 (새창열림)

'TypeScript' 카테고리의 다른 글

Next.js 프로젝트 구조의 모든 것: src/pages와 src/app 제대로 알기  (0) 2025.04.09
React에서 브라우저 창 제어하기: 새 창 열기부터 URL 추적까지  (1) 2025.03.28
tailwind CSS : 유틸리티 기반 CSS 프레임워크  (0) 2025.03.01
Zod: TypeScript 스키마 검증  (0) 2025.02.20
React Hook Form: 폼 상태 관리  (0) 2025.02.19
'TypeScript' 카테고리의 다른 글
  • Next.js 프로젝트 구조의 모든 것: src/pages와 src/app 제대로 알기
  • React에서 브라우저 창 제어하기: 새 창 열기부터 URL 추적까지
  • tailwind CSS : 유틸리티 기반 CSS 프레임워크
  • Zod: TypeScript 스키마 검증
코샵
코샵
나의 코딩 일기장
    반응형
  • 코샵
    끄적끄적 코딩 공방
    코샵
  • 전체
    오늘
    어제
    • 분류 전체보기 (513) N
      • 상품 추천 (33) N
      • MongoDB (4)
      • 하드웨어 (1) N
      • 일기장 (4)
      • Unity (138)
        • Tip (41)
        • Project (1)
        • Design Pattern (8)
        • Firebase (6)
        • Asset (2)
      • 파이썬 (127)
        • Basic (40)
        • OpenCV (8)
        • Pandas (15)
        • PyQT (3)
        • SBC(Single Board Computer) (1)
        • 크롤링 (14)
        • Fast API (29)
        • Package (6)
      • Linux (4)
      • C# (97)
        • Algorithm (11)
        • Window (7)
      • TypeScript (48)
        • CSS (10)
      • Git (11)
      • SQL (5)
      • Flutter (10)
        • Tip (1)
      • System (1)
      • BaekJoon (6)
      • Portfolio (2)
      • MacOS (1)
      • 유틸리티 (1)
      • 서비스 (6)
      • 자동화 (3)
      • Hobby (10)
        • 물생활 (10)
        • 식집사 (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

    • 다비즈
  • 공지사항

  • 인기 글

  • 태그

    파이썬
    라떼우유
    리스트
    codingcommunity
    cv2
    appdevelopment
    스마트스토어리뷰
    devlife
    셀레니움
    긴유통기한우유
    rtsp
    카페24리뷰
    스크립트 실행
    unity
    list
    programmerlife
    믈레코비타멸균우유
    Python
    programming101
    리뷰이관
    C#
    쇼핑몰리뷰
    상품 리뷰 크롤링
    카페24리뷰이관
    리뷰관리
    learntocode
    스크립트 실행 순서
    codingtips
    ipcamera
    유니티
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
코샵
Next.js에서 cookies-next로 쿠키 관리하기
상단으로

티스토리툴바