#Cookies

1 messages · Page 1 of 1 (latest)

agile isle
#
"use server";

import { cookies } from "next/headers";
import { redirect } from "next/navigation";

export async function redirectToAuth(redirectPath: string) {
  cookies().set("redirect", redirectPath);
  redirect("/api/auth");
}

Cookies can only be modified in a Server Action or Route Handler.

prime echoBOT
#

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))

In your case, you might want to move the cookie setting logic to a Server Action or Route Handler. If you need to set a cookie based on some client-side logic, you could make a fetch request to a Server Action or Route Handler that sets the cookie.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: