App Router Issue: Cookies() doesn't run inside a Server Action

I have a Server Action that I created in NextJS 14 TypeScript App Router. import { cookies } from 'next/headers' export const getTokens = async (code: string): Promise<string> => { 'use server' console.log('\n entering SERVER ACTION: getTokens(code) . . .\n'); const envIntegrationKey = process.env.NEXT_PUBLIC_DOCUSIGN_INTEGRATION_KEY const envSecretKey = process.env.DOCUSIGN_SECRET_KEY const tokenURI = 'https://account-d.docusign.com/oauth/token/'; const credentials = btoa(${envIntegrationKey}:${envSecretKey}); const reqBody = new URLSearchParams(); reqBody.append('grant_type', 'authorization_code'); reqBody.append('code', code); const response = await fetch(tokenURI, { method: 'POST', headers:{ Authorization: Basic ${credentials} }, body: reqBody }) if (response.ok) { console.log('response OK: ', response.status, 'Status Text: ', response.statusText); const data = await response.json() const accessToken: string = data.access_token; const refreshToken: string = data.refresh_token; const expiresIn: string = data.expires_in.toString(); cookies().set('accessToken', accessToken) cookies().set('refreshToken', refreshToken) //rest of code The issue is that when I hit the cookies().set() line, I get this error: Error th [Error]: Cookies can only be modified in a Server Action or Route Handler. Read more: https://nextjs.org/docs/app/api-reference/functions/cookies#cookiessetname-value-options The doc clearly says that cookies() work specifically on Server Actions (such as the one I defined) and that Server Actions are defined with the 'use server' key word. What is causing this issue?
Functions: cookies | Next.js
API Reference for the cookies function.
Solution:
https://nextjs-faq.com/server-action-call-inside-server-component-rendering - answer for the issue provided by raymclee on another server.Thanks for taking time to respond, @ACCURACY !
Jump to solution
3 Replies
ACCURACY
ACCURACY5mo ago
@PR try moving the "use server" directive at the top of your file as opposed to having it inline
PR
PR5mo ago
Tried it, no luck :/
Solution
PR
PR5mo ago
https://nextjs-faq.com/server-action-call-inside-server-component-rendering - answer for the issue provided by raymclee on another server.Thanks for taking time to respond, @ACCURACY !