Can not set cookie on server component or server action
Unanswered
Fire ant posted this in #help-forum
Fire antOP
I am creating a project using nextjs and I am making some server-side calls for fetching data. During this fetch, if there is not a desired cookie, I'd like to set it to some value. For some reason, using
This is my page.tsx file
cookies().set()
function, importing from next/headers
throw me the following error: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
at getWorkspaceId (page.tsx:24:61)
at async onGetAnalytics (page.tsx:34:25)
at async DashboardPage (page.tsx:40:20)
This is my page.tsx file
import { getAnalytics } from '@/actions/dashboard/get-analytics'
import { getRepositories } from '@/actions/workspaces/get-workspace-repositories'
import { getWorkspaces } from '@/actions/workspaces/get-workspaces'
import DashboardClientPage from '@/components/pages/DashboardPage'
import { COOKIES_KEYS } from '@/utils/cookies'
import { cookies } from 'next/headers'
async function getWorkspaceId() {
const workspaceId = cookies().get(COOKIES_KEYS.WORKSPACE_ID)
if (workspaceId?.value) return workspaceId.value
const workspaces = await getWorkspaces()
cookies().set(COOKIES_KEYS.WORKSPACE_ID, 'hello')
return workspaces[0].id
}
async function getRecentRepository(workspaceId: string) {
const recentRepositoryId = cookies().get(COOKIES_KEYS.MOST_RECENT_REPOSITORY)
if (recentRepositoryId?.value) return recentRepositoryId.value
const repositories = await getRepositories(workspaceId)
return repositories.repositories[0].id
}
async function onGetAnalytics() {
const workspaceId = await getWorkspaceId()
const repositoryId = await getRecentRepository(workspaceId)
const analytics = await getAnalytics(repositoryId)
return analytics
}
export default async function DashboardPage() {
const result = await onGetAnalytics()
return <DashboardClientPage data={result} />
}
1 Reply
Fire antOP
I have already tried setting this cookies exporting an async function from
app/actions.ts
file. I`ve already tried creating a separated file using the use server
statement. I got no success on both approaches.