# 설치
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
는 다음과 같은 핵심 기능을 제공합니다:
- 쿠키 설정 (
setCookie
) - 쿠키 가져오기 (
getCookie
) - 쿠키 삭제 (
deleteCookie
) - 모든 쿠키 확인 (
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 |