以下のように記述することでサーバーコンポーネントでCookieが使用できます。
import { cookies } from 'next/headers'
async function getData() {
const res = await fetch("http//sample.com", {
method: 'GET',
headers: {
Cookie: cookies().toString(),
},
cache: 'no-cache',
})
if (!res.ok) {
throw new Error('Failed to fetch data')
}
return res.json()
}
export default async function Sample() {
const data = await getData()
return (
<div>...</div>
)
}
リクエストはできますが、HTTPではストリーミング開始後にCookieを設定することができないため、レスポンスのCookieをサーバーコンポーネントでセットすることはできません。
レスポンスのCookieをセットする場合には、Middleware、Server Actions、Route Handler、のいずれかを使用する必要があります。
サーバーコンポーネントでCookieをセットする必要がある場合には以下を参照してください。
上記のライブラリはHttpOnly
は設定できないようです。