#Can not set cookie on server component or server action

2 messages · Page 1 of 1 (latest)

elfin stirrup
#

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 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} />
}

west oakBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)