Secure 標記的 Cookie **僅在 HTTPS 請求中發送**,HTTP 請求不會攜帶,防止中間人竊聽。
document.cookie = "name=EX; expires=60*24*7; secure=true";
開發者工具 Application → Cookies 可見 Secure 勾選。| 屬性 | 建議值 | 說明 |
|---|---|---|
| Secure | true | 生產環境強制 HTTPS 時必開 |
| HttpOnly | true | 防 XSS 竊取,JS 無法讀取 document.cookie |
| SameSite | Strict / Lax | 防 CSRF,現代瀏覽器默認 Lax |
| Domain | 最小必要域 | 避免過寬域導致子域洩露 |
| Path | 最小必要路徑 | 同上 |
| Expires/Max-Age | 合理過期時間 | 避免長期存活增加風險面 |
document.cookie = [
'sessionId=abc123',
'Secure',
'HttpOnly',
'SameSite=Lax',
'Domain=example.com',
'Path=/',
'Max-Age=2592000' // 30天
].join('; ');
lvh.me (解析到 127.0.0.1) + mkcert 簽發本地憑證啟用 HTTPS。Secure 是 Cookie 安全基線三件套(Secure + HttpOnly + SameSite)之一。**全站 HTTPS 是前提**,未遷移 HTTPS 前請勿啟用 Secure,否則 Cookie 失效導致登錄狀態丟失。