Cookie 是 HTTP 協議中攜帶狀態的核心機制,雖然現代前端有 localStorage、sessionStorage、IndexedDB,但 Cookie 仍是伺服器端識別用戶、SSO、跨子域共享、HttpOnly 防 XSS的唯一選擇。本文提供完整的原生操作封裝、屬性詳解、安全屬性配置、SameSite 策略與框架整合模式。
| 屬性 | 說明 | 範例 | 必要性 |
|---|---|---|---|
| name=value | 鍵值對,值需 encodeURIComponent | token=abc123 | 必填 |
| expires | 過期 GMT 字串,缺失則為 Session Cookie(關閉瀏覽器失效) | expires=Mon, 15 Jun 2025 06:30:00 GMT | 選填 |
| max-age | 秒數,優先級高於 expires(IE 支援度較舊) | max-age=2592000 (30天) | 建議同時設定 |
| domain | 可讀取的域名,預設為設定 Cookie 的主機名(不含 port) | domain=.example.com (含子域) | 跨子域必填 |
| path | 可讀取的路徑前綴 | path=/ | 建議固定 / |
| Secure | 僅 HTTPS 傳輸 | Secure | 生產環境必填 |
| HttpOnly | 禁止 JS 讀取(document.cookie 不可見),防 XSS 竊取 | HttpOnly | 敏感 Cookie 必填(需後端設定) |
| SameSite | 跨站請求攜帶策略:Strict/Lax/None | SameSite=Lax | 現代瀏覽器預設 Lax |
/**
* Cookie 統一操作類
* 所有方法靜態,無副作用,支援 TypeScript
*/
class CookieUtil {
/** 設定 Cookie */
static set(name, value, options = {}) {
const {
days = 30,
maxAge, // 秒,優先於 days
domain,
path = '/',
secure = location.protocol === 'https:',
sameSite = 'Lax',
encode = encodeURIComponent
} = options;
let cookie = `${encode(name)}=${encode(String(value))}`;
if (maxAge !== undefined) {
cookie += `;max-age=${maxAge}`;
} else if (days !== null) {
const expires = new Date(Date.now() + days * 864e5).toUTCString();
cookie += `;expires=${expires}`;
}
if (domain) cookie += `;domain=${domain}`;
if (path) cookie += `;path=${path}`;
if (secure) cookie += ';Secure';
if (sameSite) cookie += `;SameSite=${sameSite}`;
document.cookie = cookie;
}
/** 讀取 Cookie */
static get(name, decode = decodeURIComponent) {
const cookies = document.cookie.split(';');
const prefix = `${encodeURIComponent(name)}=`;
for (const c of cookies) {
const trimmed = c.trimStart();
if (trimmed.startsWith(prefix)) {
return decode(trimmed.slice(prefix.length));
}
}
return null;
}
/** 刪除 Cookie(設定過期為過去) */
static remove(name, options = {}) {
// 必須指定相同的 domain/path 才能刪除對應 Cookie
this.set(name, '', { ...options, days: -1, maxAge: 0 });
}
/** 取得所有 Cookie 物件 */
static getAll(decode = decodeURIComponent) {
const result = {};
document.cookie.split(';').forEach(c => {
const [k, ...v] = c.trim().split('=');
if (k) result[decode(k)] = decode(v.join('='));
});
return result;
}
/** 檢查 Cookie 是否存在 */
static has(name) {
return this.get(name) !== null;
}
}
// 導出
if (typeof module !== 'undefined') module.exports = CookieUtil;
export default CookieUtil;
// 設定:30 天、全域、HTTPS、Lax
CookieUtil.set('user_token', 'abc123', { days: 30, domain: '.example.com', secure: true });
// 設定:Session Cookie(關閉瀏覽器失效)、Strict
CookieUtil.set('csrf_token', 'xyz', { days: null, sameSite: 'Strict' });
// 讀取
const token = CookieUtil.get('user_token');
// 刪除(需指定原 domain/path)
CookieUtil.remove('user_token', { domain: '.example.com', path: '/' });
// 批次讀取
console.log(CookieUtil.getAll()); // { user_token: 'abc123', ... }
| 值 | 行為 | 適用場景 |
|---|---|---|
| Strict | 完全禁止跨站攜帶(含導航鏈接) | 高安全操作(修改密碼、轉帳) |
| Lax (預設) | 允許安全跨站導航(GET 鏈接),禁止 POST/iframe/子資源 | 大多數身份驗證 Cookie |
| None | 所有跨站請求皆攜帶,**必須搭配 Secure** | 跨域嵌入(iframe、圖片、API)、SSO |
// 前端呼叫登出 API,由後端回應 Set-Cookie: token=; HttpOnly; Secure; SameSite=Lax; Max-Age=0; Path=/
async function logout() {
await fetch('/api/logout', { method: 'POST', credentials: 'include' });
// 後端負責清除 HttpOnly Cookie
location.href = '/login';
}
domain=.example.com(前綴點可選,現代瀏覽器同義)a.example.com, b.example.com)均可讀寫script-src 降低 XSS 風險
// plugins/cookie.js
import CookieUtil from '@/utils/CookieUtil';
export default {
install(app, options) {
app.config.globalProperties.$cookie = CookieUtil;
app.provide('cookie', CookieUtil);
}
}
// 組件中
const cookie = inject('cookie');
cookie.set('theme', 'dark');
// context/CookieContext.jsx
import { createContext, useContext, useCallback } from 'react';
import CookieUtil from '@/utils/CookieUtil';
const CookieContext = createContext(CookieUtil);
export function CookieProvider({ children }) {
return {children} ;
}
export function useCookie() {
return useContext(CookieContext);
}
// 組件中
const cookie = useCookie();
cookie.set('lang', 'zh-TW');
Cookie 操作看似簡單,但屬性組合決定安全性與可用性。請將 CookieUtil 納入專案共用庫,統一 Secure、SameSite、domain、path 預設值,並建立 Code Review 機制確保敏感 Cookie 皆設 HttpOnly。現代架構下,認證 Token 建議放 HttpOnly Cookie,業務資料用 localStorage/IndexedDB,分工明確才能兼顧安全與體驗。