You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js 15中Middleware设置Cookie后页面首次读取为undefined问题

Next.js 15 App Router中Middleware设置Cookie后,Server Component首次读取返回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).*)',
}
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>
  )
}
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-

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 15:58:16