1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Next.js】Server Actionsからのリクエストにcookieをセットする方法

Last updated at Posted at 2024-11-06

すべてのCookie

fetchheadersCookie: cookieStore.toString()を記述するとブラウザに設定されているすべてのCookieをセットできます。

'use server'

// ...

export async function sample() {
  const cookieStore = await cookies()
  const res = await fetch(
    `http://example.com/sample`,
    {
      method: 'POST',
      headers: {
        // ...
        Cookie: cookieStore.toString(),
      },
      // ...
    },
  )

  // ...
}

特定のCookie

特定のCookieのみセットする場合には以下のようにします。

'use server'

// ...

export async function sample() {
  const cookieStore = await cookies()
  const sampleCookie = cookieStore.get('sample')
  const res = await fetch(
    `http://example.com/sample`,
    {
      method: 'POST',
      headers: {
        // ...
        Cookie: `${sampleCookie?.name}=${sampleCookie?.value}`,
      },
      // ...
    },
  )

  // ...
}

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?