Next.js 15中Middleware设置Cookie后页面首次读取为undefined问题
业务场景中需根据用户登录状态展示按钮:登录时显示LOGOUT,未登录时显示LOGIN。但在采用App Router的Next.js 15项目中遇到异常:在middleware.ts内设置Cookie后,嵌套的Server Component首次读取该Cookie时返回undefined,尽管浏览器DevTools中已存在该Cookie,仅刷新页面后才能正常读取。
项目结构
. ├── bun.lockb ├── next.config.ts ├── next-env.d.ts ├── package.json ├── src │ ├── app │ │ ├── cookie-block.tsx │ │ ├── layout.tsx │ │ └── page.tsx │ ├── functions │ │ └── auth-cookie.ts │ └── middleware.ts └── tsconfig.json
相关代码
src/middleware.ts
import { NextResponse } from 'next/server' import { getAuthCookie, setAuthCookie } from './functions/auth-cookie' export default async function middleware() { // # ensure cookie exists const authToken = await getAuthCookie() if (!authToken) await setAuthCookie() return NextResponse.next() } export const config = { matcher: '/((?!_next/static|favicon.ico).*)', }
src/functions/auth-cookie.ts
import { cookies } from 'next/headers' const COOKIE_NAME = 'auth' export const setAuthCookie = async () => { const cookieStore = await cookies() const hardcodedValue = 'abcd123' cookieStore.set(COOKIE_NAME, hardcodedValue, {}) } export const getAuthCookie = async () => { const cookieStore = await cookies() const cookie = cookieStore.get(COOKIE_NAME) return cookie?.value }
src/app/page.tsx
import { CookieBlock } from './cookie-block' export default function Home() { return ( <div className="bg-orange-400 flex justify-center h-screen w-screen items-center flex-col gap-y-16"> <h1 className="font-extrabold text-4xl">This page is just for demo</h1> <CookieBlock /> </div> ) }
src/app/cookie-block.tsx
import { getAuthCookie } from '@/functions/auth-cookie' export const CookieBlock = async () => { const authToken = await getAuthCookie() return ( <div className="bg-orange-700 text-center rounded-xl p-5"> <h3 className="text-2xl font-bold">Your cookie is:</h3> <h4> <i>{authToken ?? 'IT IS UNDEFINED'}</i> </h4> </div> ) }
演示效果

内容的提问来源于stack exchange,提问作者Islam Y-
相关产品推荐
相关产品推荐

