概览在 Next.js 15 的 App Router 中,`cookies()` 与 `headers()` 可在服务器组件与路由内读取请求上下文;在 Middleware 中使用 `NextRequest/NextResponse` 读写。合理治理可实现一致的鉴权与个性化。RSC 读取上下文// app/dashboard/page.tsx import { cookies, headers } from 'next/headers' export default async function Page() { const sid = cookies().get('session')?.value const ua = headers().get('user-agent') return (<pre>{JSON.stringify({ sid, ua }, null, 2)}</pre>) } Route Handlers 设置响应头// app/api/info/route.ts export async function GET() { return new Response('ok', { headers: { 'x-app': 'v1' } }) } Middleware 读写 Cookie/重写import { NextResponse } from 'next/server' import type { NextRequest } from 'next/server' export function middleware(req: NextRequest) { const url = req.nextUrl.clone() const sid = req.cookies.get('session')?.value if (!sid && url.pathname.startsWith('/dashboard')) { url.pathname = '/login' const res = NextResponse.redirect(url) res.cookies.set('last', Date.now().toString(), { path: '/' }) return res } return NextResponse.next() } export const config = { matcher: ['/((?!_next|api/public).*)'] } 治理要点在 RSC 中使用 `cookies/headers` 读取请求上下文;在客户端组件中避免直接依赖。在 Middleware 中做鉴权与分流;对响应使用 `NextResponse` 统一读写 Cookie 与头。与安全策略协同(SameSite、Secure、CSP 等),避免泄露与跨站风险。验证与指标Next.js:15.0+;Edge Runtime:兼容上下文读取与写入一致;鉴权与分流稳定

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部
2.149450s