#Cookies
1 messages · Page 1 of 1 (latest)
Hi @agile isle. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
The error message you're seeing is correct. In Next.js, cookies can only be modified in a Server Action or Route Handler. The function you've written seems to be neither of these.
A Server Action is a function that you export from a file in the pages/api directory. It's a function that runs on the server side when a certain API route is hit. Here's an example of a Server Action that sets a cookie:
'use server'
import { cookies } from 'next/headers'
export async function exampleAction() {
// Set cookie
cookies().set('name', 'Delba')
}
(Source: Next.js Docs (https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations#examples-cookies))
A Route Handler is a function that you export from a file in the pages/api directory. It's a function that runs on the server side when a certain route is hit. Here's an example of a Route Handler that sets a cookie:
import { cookies } from 'next/headers'
export async function GET(request: Request) {
const cookieStore = cookies()
const token = cookieStore.get('token')
return new Response('Hello, Next.js!', {
status: 200,
headers: { 'Set-Cookie': `token=${token.value}` },
})
}
(Source: Next.js Docs (https://nextjs.org/docs/app/building-your-application/routing/route-handlers#dynamic-functions))