萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript Cookie 完整操作指南:設定、讀取、刪除、選項詳解與安全最佳實踐

Cookie 是 HTTP 協議中攜帶狀態的核心機制,雖然現代前端有 localStorage、sessionStorage、IndexedDB,但 Cookie 仍是伺服器端識別用戶、SSO、跨子域共享、HttpOnly 防 XSS的唯一選擇。本文提供完整的原生操作封裝、屬性詳解、安全屬性配置、SameSite 策略與框架整合模式。

Cookie 屬性完整對照表

屬性說明範例必要性
name=value鍵值對,值需 encodeURIComponenttoken=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/NoneSameSite=Lax現代瀏覽器預設 Lax

原生封裝工具類(ESM/CommonJS 通用)


/**
 * 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', ... }

進階主題

1. SameSite 策略選擇

值行為適用場景
Strict完全禁止跨站攜帶(含導航鏈接)高安全操作(修改密碼、轉帳)
Lax (預設)允許安全跨站導航(GET 鏈接),禁止 POST/iframe/子資源大多數身份驗證 Cookie
None所有跨站請求皆攜帶,**必須搭配 Secure**跨域嵌入(iframe、圖片、API)、SSO

2. HttpOnly Cookie:前端無法操作,如何登出?


// 前端呼叫登出 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';
}

3. 子域共享 Cookie(.example.com)

  • 設定 domain=.example.com(前綴點可選,現代瀏覽器同義)
  • 所有子域(a.example.com, b.example.com)均可讀寫
  • 無法跨不同主域(example.com vs other.com)

4. 安全性檢查清單

  • ✅ 敏感 Cookie(token、sessionId)必須 HttpOnly + Secure + SameSite=Lax/Strict
  • ✅ 非敏感追蹤 Cookie 可無 HttpOnly,但建議 SameSite=Lax
  • ✅ 絕不 在 Cookie 存放機密資料(密碼、信用卡、個資)
  • ✅ 定期輪換 Secret Key、實作 Token 刷新機制
  • ✅ CSP 標頭限制 script-src 降低 XSS 風險

框架整合模式

Vue 3 Plugin


// 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');

React Context + Hook


// 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,分工明確才能兼顧安全與體驗。

copyright © 萬盛學電腦網 all rights reserved