Next.js应用中如何在子域名间共享Cookie(本地与生产环境)
核心原理
Cookie的domain属性决定了哪些域名可访问该Cookie。将其设置为带前缀点的父域名,即可实现所有子域名共享Cookie:
- 生产环境:父域设为
.company.com,app.company.com和exd.company.com均可访问 - 开发环境:父域设为
.localhost,app.localhost:3000和exd.localhost:3000均可访问
开发环境配置
1. 配置本地子域名
修改系统hosts文件,将子域名指向localhost:
127.0.0.1 app.localhost 127.0.0.1 exd.localhost
2. 设置Cookie规则
在Next.js中设置Cookie时,指定domain: '.localhost',同时关闭secure(开发环境无HTTPS)。
生产环境配置
1. 确保HTTPS环境
生产环境必须使用HTTPS,否则带secure属性的Cookie会被浏览器拒绝。
2. 设置Cookie规则
指定domain: '.company.com',同时开启secure: true。
Next.js具体实现代码示例
(1)在App Router的API路由中设置Cookie(连接钱包后)
import { cookies } from 'next/headers'; export async function POST(request: Request) { const { walletAddress } = await request.json(); const isProduction = process.env.NODE_ENV === 'production'; cookies().set('walletAddress', walletAddress, { httpOnly: false, // 若需前端访问钱包地址则设为false,仅后端使用可设为true secure: isProduction, sameSite: 'lax', // 适配跨子域名跳转场景 domain: isProduction ? '.company.com' : '.localhost', path: '/', // 全局路径可访问 maxAge: 60 * 60 * 24 * 7, // 7天有效期,按需调整 }); return Response.json({ success: true, redirectTo: 'https://exd.company.com' }); }
(2)在exd子域名页面获取Cookie
客户端组件获取:
'use client'; export default function ExdHome() { const getWalletAddress = () => { if (typeof window === 'undefined') return null; return document.cookie.split('; ') .find(row => row.startsWith('walletAddress=')) ?.split('=')[1]; }; const walletAddress = getWalletAddress(); return ( <div> {walletAddress ? `当前钱包地址:${walletAddress}` : '未连接钱包'} </div> ); }
服务器组件获取:
import { cookies } from 'next/headers'; export default function ExdServerHome() { const walletAddress = cookies().get('walletAddress')?.value; return ( <div> {walletAddress ? `当前钱包地址:${walletAddress}` : '未连接钱包'} </div> ); }
关键注意事项
sameSite属性:跨子域名跳转时推荐用lax,既保证安全又能在跳转后携带Cookie;若需严格隔离可设为strict,但可能影响跳转后的Cookie获取。path必须设为/,确保所有路径下的页面都能访问该Cookie。- 开发环境下,Next.js开发服务器直接用
npm run dev启动即可,通过app.localhost:3000和exd.localhost:3000访问。
内容的提问来源于stack exchange,提问作者kehlani
相关产品推荐
相关产品推荐

