【Next.js】Server ActionではCookieをsetできない
こんにちは、フリーランスエンジニアの太田雅昭です。
Server ActionでのCookie set
公式では、2025年4月13日現在下記のように書かれています。
You can use the (await cookies()).set(name, value, options) method in a Server Action or Route Handler to set a cookie. The options object is optional.
https://nextjs.org/docs/app/api-reference/functions/cookies
これはどうよんでも、以下のように解釈できます。
「cookiesのsetは、Server Actionで使える!」
どう読んでも、
「cookiesのsetは、Server Actionで使える!」
としか読めません。
しかし実際は、Server Actionではcookies 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
このエラー文、どう読んでも納得いかないのですが、そういうことのようです。繰り返しますが、Server Actionではcookies setはエラーになります。
回避策
route.tsでapiとしてアクセスするか、middlewareで返すか、クッキーデータをクライアントで受け取ってsetするかのどれかになるようです。
これまでも何度か同じ事態になっていた気がします。やはり都度、まとめないと忘れますね。