紀錄工作經驗、相關知識,解決技術相關問題。

Next

Next.js cookies 用法:get、set、delete 寫入位置、options 屬性與 Cache Components 讀取限制

Next.js cookies 用法:get、set、delete 寫入位置、options 屬性與 Cache Components 讀取限制 特色圖片

Next.js cookies 是 next/headers 提供的非同步函式:在 Server Components 讀取請求帶來的 cookie,在 Server Functions 或 Route Handlers 讀取與寫入 cookie。本文以 Next.js 16.4.3 專案的範例,說明 get、getAll、has、set、delete 的用法、為什麼寫入只能放在 Server Function 或 Route Handler、set 的 options 對應到哪些 Set-Cookie 屬性,以及開啟 Cache Components 後讀取 cookie 要注意的 <Suspense> 與 "use cache" 限制。Cookie、localStorage 與 sessionStorage 的基本差異可以先看 前端資料儲存 Cookie、localStorage、sessionStorage 使用場景、限制、差異。

cookies 的基本寫法與方法

cookies() 回傳 Promise,要先 await 才能拿到 cookie 物件:

// app/page.tsx
import { cookies } from 'next/headers'

export default async function Page() {
  const cookieStore = await cookies()
  const theme = cookieStore.get('theme')
  return <p>theme={theme?.value}</p>
}

官方文件列出的方法:

方法回傳說明
get('name')物件傳入名稱,回傳含 name 與 value 的物件
getAll()物件陣列傳入名稱時回傳符合名稱的 cookie;不傳名稱回傳全部
has('name')Boolean該名稱的 cookie 是否存在
set(name, value, options)-設定要送出的 cookie
delete(name)-刪除 cookie
toString()Stringcookie 的字串表示

下面的元件把五個讀取方法的結果都印出來:

import { cookies } from 'next/headers'

async function CookieInfo() {
  const cookieStore = await cookies()
  return (
    <div>
      <p>get: {JSON.stringify(cookieStore.get('theme'))}</p>
      <p>has: {String(cookieStore.has('theme'))}</p>
      <p>getAll: {JSON.stringify(cookieStore.getAll())}</p>
      <p>getAll(tag): {JSON.stringify(cookieStore.getAll('tag'))}</p>
      <p>toString: {cookieStore.toString()}</p>
    </div>
  )
}

瀏覽器帶著 theme=dark 與 lang=zh-TW 兩個 cookie 請求時,輸出如下;沒有任何 cookie 時,get 回傳 undefined、has 為 false、getAll() 為空陣列:

cookies 讀取方法的輸出:get 回傳 name 與 value 物件、has 為 true、getAll 列出 theme 與 lang、toString 為 theme=dark; lang=zh-TW

Next.js 16.4.3 next start、無頭 Chrome 156 開啟頁面的畫面。

請求的 Cookie 標頭帶了兩個同名 cookie(tag=a; tag=b)時,getAll('tag') 只回傳 [{"name":"tag","value":"b"}],前一個值不會出現在結果裡,需要分辨的 cookie 要用不同名稱。

cookies 屬於 Request-time API,回傳值無法事先知道,在 layout 或 page 使用會讓路由改為動態渲染。

寫入只能在 Server Function 或 Route Handler

讀取 cookie 讀的是瀏覽器隨請求送來的 Cookie 標頭;寫入則是伺服器在回應加上 Set-Cookie 標頭,由瀏覽器自己儲存。官方文件說明,HTTP 不允許在串流開始後設定 cookie,所以 set 與 delete 只能在 Server Function 或 Route Handler 呼叫,Server Component 渲染期間不支援寫入。

在 Server Component 裡呼叫 set,伺服器會丟出這個錯誤:

Error: Cookies can only be modified in a Server Action or Route Handler. Read more: https://nextjs.org/docs/app/api-reference/functions/cookies#options

這個元件包在 <Suspense> 內時,next build 照常通過,請求該頁也回 HTTP 200,錯誤只出現在伺服器終端機,cookie 沒有寫入。上線前要確認寫入的程式碼不在元件渲染流程裡。

在 Server Function(表單 action)寫入

// app/actions.ts
'use server'

import { cookies } from 'next/headers'

export async function setTheme(formData: FormData) {
  const theme = String(formData.get('theme') ?? 'light')
  const cookieStore = await cookies()
  cookieStore.set('theme', theme, {
    httpOnly: true,
    secure: true,
    sameSite: 'lax',
    maxAge: 60 * 60 * 24 * 30,
  })
}

export async function deleteTheme() {
  const cookieStore = await cookies()
  cookieStore.delete('theme')
}
// app/page.tsx
import { Suspense } from 'react'
import { cookies } from 'next/headers'
import { setTheme, deleteTheme } from './actions'

async function CurrentTheme() {
  const cookie = (await cookies()).get('theme')
  return <p>theme={cookie?.value || '(none)'}</p>
}

export default function Page() {
  return (
    <>
      <Suspense fallback={<p>Loading...</p>}>
        <CurrentTheme />
      </Suspense>
      <form action={setTheme}>
        <input type="hidden" name="theme" value="dark" />
        <button type="submit">set theme=dark</button>
      </form>
      <form action={deleteTheme}>
        <button type="submit">delete theme</button>
      </form>
    </>
  )
}

按下「set theme=dark」後,Server Action 的 POST 回應帶有這個標頭:

set-cookie: theme=dark; Path=/; Expires=Thu, 03 Dec 2026 08:04:09 GMT; Max-Age=2592000; Secure; HttpOnly; SameSite=lax

path 沒有指定也會輸出 Path=/,這是 options 裡唯一有預設值的欄位;指定 maxAge 時,回應同時帶有換算好的 Expires。因為設了 httpOnly,瀏覽器裡的 document.cookie 讀到的是空字串。

按下 set 按鈕後,同一頁面的 theme 顯示為 dark,get 回傳 name 為 theme、value 為 dark 的物件

Next.js 16.4.3 next start、無頭 Chrome 156:按下表單按鈕後,畫面直接更新為新的 cookie 值。

官方文件說明,Server Function 當成 Server Action 使用(例如傳給 <form> 的 action)時,設定或刪除 cookie 後,Next.js 可以在同一次伺服器往返回傳更新後的 UI 與新資料;畫面不會 unmount,但依賴伺服器資料的 effect 會重新執行。要連快取資料一起更新,在函式內呼叫 revalidatePath 或 revalidateTag。Server Function 的寫法與安全注意事項可參考 Next.js use server 指令用法。

在 Route Handler 寫入

// app/api/session/route.ts
import { cookies } from 'next/headers'

export async function GET() {
  const cookieStore = await cookies()
  cookieStore.set('session', 'abc123', {
    httpOnly: true,
    secure: true,
    sameSite: 'strict',
    maxAge: 3600,
  })
  cookieStore.set({ name: 'lang', value: 'zh-TW', path: '/', priority: 'high' })
  return Response.json({ ok: true })
}

set 可以傳名稱、值、options 三個參數,也可以傳一個含 name、value 的物件。回應的兩個 Set-Cookie:

set-cookie: session=abc123; Path=/; Expires=Tue, 03 Nov 2026 09:00:31 GMT; Max-Age=3600; Secure; HttpOnly; SameSite=strict
set-cookie: lang=zh-TW; Path=/; Priority=high

Route Handler 的其他寫法見 Next.js route.js 用法。

set 的 options 與 Set-Cookie 屬性

option型別Set-Cookie 屬性的作用(依 MDN)
expiresDate指定到期時間
maxAgeNumber(秒)幾秒後到期;0 或負數立即過期;和 Expires 同時存在時以 Max-Age 為準
domainString該網域與所有子網域都會收到;省略時只回傳給設定它的主機
pathString,預設 '/'請求網址包含這個路徑才送出;不是安全機制,無法阻止其他路徑讀取
secureBoolean只在 https: 請求送出(localhost 例外)
httpOnlyBooleanJavaScript(例如 document.cookie)無法存取,但 fetch() 發出的請求仍會帶上
sameSiteBoolean、'lax'、'strict'、'none'strict 只在來自同一網站的請求送出;lax 另允許頂層導覽且使用安全方法(不含 POST)的跨站請求;none 跨站也送出,且必須同時設定 secure
priority"low"、"medium"、"high"指定 cookie 的優先順序
partitionedBoolean以分區儲存(CHIPS),必須同時設定 secure

expires 與 maxAge 都沒設定時是 session cookie,瀏覽器關閉時移除,DevTools 的 Expires 欄會顯示 Session,原因見 Cookie Expires 顯示為 Session 是什麼意思?。

刪除 cookie 的三種寫法

官方文件列出三種刪除方式,都要寫在 Server Function 或 Route Handler:

'use server'

import { cookies } from 'next/headers'

export async function deleteCookie() {
  const cookieStore = await cookies()
  cookieStore.delete('session')                         // 1. delete()
  // cookieStore.set('session', '')                     // 2. 同名、空值
  // cookieStore.set('session', 'value', { maxAge: 0 }) // 3. maxAge 設為 0
}

三種寫法各自送出的 Set-Cookie:

delete()      → set-cookie: session=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT
set 空值      → set-cookie: session=; Path=/
maxAge: 0     → set-cookie: session=value; Path=/; Max-Age=0

delete() 送出的是 1970 年的過期時間,maxAge: 0 依 MDN 的說明會立即過期,兩者都讓瀏覽器移除這個 cookie。第二種只把值改成空字串,回應沒有 Expires 或 Max-Age。

使用 delete() 還有兩個條件:要和當初 set 時屬於同一個網域(萬用字元網域要完全符合子網域),而且要在同一個協定(HTTP 或 HTTPS)下執行。

上一節的表單範例按下「delete theme」後,同一次往返重新渲染的 get('theme') 回傳 {"name":"theme","value":""},不是 undefined,所以範例用 cookie?.value || '(none)' 判斷;重新整理頁面後 get('theme') 才是 undefined。

Cache Components 下讀取 cookie 的位置

要放在 Suspense 裡

開啟 cacheComponents 時,在 <Suspense> 外呼叫 cookies() 會讓路由無法 prerender。把本文第一段的寫法直接放在 page,next build 會失敗:

Error: Route "/tests/nextjs-cookies/top": Next.js encountered uncached or runtime data during prerendering.

`fetch(...)`, `cookies()`, `headers()`, `params`, `searchParams`, or `connection()` accessed outside of `<Suspense>` prevents the route from being prerendered, blocking the page load and leading to a slower user experience.

修法是把讀取 cookie 的元件包進 <Suspense>,前面的讀取與表單範例都是這樣寫,建置後路由標記為 ◐,預先產生的 HTML 只有 fallback,cookie 的內容在請求時串流。<Suspense> 邊界要盡量貼近讀取 cookie 的元件,讓其他內容留在靜態外殼。

例外是 <html lang>、<html data-theme> 這類根元素屬性:根元素不能包進 <Suspense>,官方建議改用繪製前執行的用戶端腳本設定,並在 <html> 加上 suppressHydrationWarning。

不能在 use cache 裡讀取

"use cache" 函式內呼叫 cookies(),next build 會停在這個錯誤:

Error: Route "/tests/nextjs-cookies/cached": `cookies()` can't be read inside `"use cache"`. Read it outside the cached function and pass what you need as an argument.

做法是在快取函式外讀取 cookie,再把值當參數傳進去,cookie 值會成為快取鍵的一部分:

import { cookies } from 'next/headers'

async function getGreeting(theme: string) {
  'use cache'
  return `cached greeting for ${theme} @ ${new Date().toISOString()}`
}

async function Greeting() {
  const theme = (await cookies()).get('theme')?.value ?? 'light'
  return <p>{await getGreeting(theme)}</p>
}

Greeting 外層同樣要包 <Suspense>。帶著 theme=dark 連續請求兩次,回傳的時間相同,代表命中快取:

cached greeting for dark @ 2026-11-03T08:00:32.655Z
cached greeting for dark @ 2026-11-03T08:00:32.655Z

快取函式的寫法見 Next.js use cache 指令用法。

use cache: private 可以讀取

'use cache: private' 允許在快取範圍內呼叫 cookies(),適合不容易改成「外面讀取再傳參數」的函式:

import { cookies } from 'next/headers'

async function getTheme() {
  'use cache: private'
  const theme = (await cookies()).get('theme')?.value
  return theme ?? 'light'
}

這段在開啟 Cache Components 的專案可以通過 next build,請求帶 theme=dark 時回傳 dark。'use cache: private' 的快取位置與適用情境見 Next.js use cache: private 指令用法。元件沒有讀取 cookie、卻要在請求時才渲染的情況,改用 Next.js connection。

cookies 是非同步函式:Next.js 15 與 16 的差異

Next.js 14 以前 cookies() 是同步函式。v15.0.0-RC 改為非同步,Next.js 15 期間仍保留同步存取的相容行為;Next.js 16 完全移除同步存取,cookies()、headers()、draftMode()、params、searchParams 都只能非同步取得,要用 async/await 或 React 的 use。

舊專案從 Next.js 15 升級、仍有同步寫法時,官方升級說明提供 codemod:

npx @next/codemod@canary next-async-request-api .

版本歷史

版本變更
v13.0.0推出 cookies
v15.0.0-RCcookies 改為非同步函式,提供 codemod
v16.0.0移除同步存取的相容行為

參考資料與延伸閱讀

發佈留言