// utils/cookie.ts import Cookies from 'js-cookie' import { parse } from 'cookie' // 服务端解析 Cookie(从请求头) export const getServerCookie = (key: string, reqHeaders?: Headers) => { // if (typeof window !== 'undefined') return undefined // 仅服务端使用 const cookieHeader = reqHeaders?.get('cookie') || '' const parsed = parse(cookieHeader) console.log("Server Get Cookie:", parsed); return parsed[key] } // 客户端读取 Cookie export const getClientCookie = (key: string): string | undefined => { // if (typeof window === 'undefined') return undefined return Cookies.get(key) } // 统一获取 Cookie(自动判断环境) export const getCookie = (key: string, reqHeaders?: Headers) => { if (typeof window !== 'undefined') { console.log("CSR获取"); return getClientCookie(key) } else { console.log("SSR获取", reqHeaders); return getServerCookie(key, reqHeaders) } } // 设置 Cookie(客户端和服务端) export const setCookie = (key: string, value: string, expiresDays: number = 7) => { // if (typeof window !== 'undefined') { Cookies.set(key, value, { // httpOnly: true, expires: expiresDays, path: '/', secure: process.env.NODE_ENV === 'production', // 生产环境启用 HTTPS sameSite: 'Lax' // 防止 CSRF 攻击 }) // } } // 移除 Cookie export const removeCookie = (key: string) => { // if (typeof window !== 'undefined') { Cookies.remove(key) // } }