PR
PR
TTCTheo's Typesafe Cult
Created by PR on 2/5/2024 in #questions
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?
6 replies