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-10-03

Cookieをクライアントにセットするための関数を作成

クライアントでCookieをセットするための関数を以下の手順で作成します。

まずset-cookie-parserをインストールします。

ターミナル
npm install --save set-cookie-parser

次にproxy-server-cookies.tsを作成します。
Server ActionsでのSet-Cookieヘッダーの値をcookies().setでセットしなおしています。

proxy-server-cookies.ts
import 'server-only'
import { cookies } from 'next/headers'
import setCookieParser from 'set-cookie-parser'

export function proxyServerCookies(headers: Headers) {
  const setCookie = headers.get('set-cookie')

  if (setCookie !== null) {
    const splitCookieHeaders = setCookieParser.splitCookiesString(setCookie)
    const cookieObjects = setCookieParser.parse(splitCookieHeaders)

    cookieObjects.forEach((cookieObject) => {
      const { name, value, sameSite, ...rest } = cookieObject
      cookies().set(name, value, {
        sameSite: sameSite === 'strict' ? 'strict' : 'lax',
        ...rest,
      })
    })
  }
}

上記の関数を使用してCookieをセットする

以下のように作成した関数を使用します。

'use server'

import { cookies } from 'next/headers'
import { proxyServerCookies } from './proxy-server-cookies'

export async function sample() {
  try {
    const res = await fetch(
      "http://example.com/sample",
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Cookie: cookies().toString(),
        },
        body: JSON.stringify({
          // ...
        }),
      }
    )

    // ...
  
    proxyServerCookies(res.headers)

    // ...
  } catch (err) {
    // ...
  }
}

参考

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?