8
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Next.js】サーバーコンポーネントでCookieを使用する方法

Last updated at Posted at 2023-10-19

以下のように記述することでサーバーコンポーネントで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は設定できないようです。

8
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?