Next.js Discord

Discord Forum

nextjs cookies probleme

Unanswered
Checkered Giant posted this in #help-forum
Open in Discord
Checkered GiantOP
hello, i got some trouble using cookie in nextJs with app router, i'm ok to set cookie in my middleware, i can also get my cookie in my page but i cant set my cookie in page or api, if i try with api like :
'use server';

import { NextResponse } from "next/server";
import { cookies } from 'next/headers'
 
async function create() {
  const oneDay = 24 * 60 * 60 * 1000
  cookies().set('name', 'value', { expires: Date.now() - oneDay })
}

export async function GET(request) {
    
    let response = NextResponse.json({
        status:'succes',
    },{ status: 200 })

    create()
    
    return response
}

and if i try with a page nextJs tell me "Cookies can only be modified in a Server Action or Route Handler.", so i dont know how to do it, i also try some module like 'next-cookie', 'js-cookie' ect but that dont work so i dont know how to do it
if someone can help me please tell me, Thanks!

45 Replies

Why are you defining Route Handlers and Server Actions in the same file? "use server" directive cannot be used in a route handler it's only used to define server actions, seperate the two, then try again.
also route.ts cannot export any functions that are not HTTP methods.
@Plague Why are you defining Route Handlers and Server Actions in the same file? "use server" directive cannot be used in a route handler it's only used to define server actions, seperate the two, then try again.
Checkered GiantOP
So i need to create another files like "src/utils/cookies.ts" to export a server actien and import the cookie function in the route.ts?
if if this isn't it, what am I supposed to do? (thanks for the help)
because i am trying to set my cookies in my api or my page when the user login/register but i can't get it
@Checkered Giant So i need to create another files like "src/utils/cookies.ts" to export a server actien and import the cookie function in the route.ts?
You’re setting the cookies in the server action in the example above so create an actions.ts file put use server at the top make your server action and use it whereever you’re calling this route handler from the looks of it you don’t even need that route handler
Yes
Checkered GiantOP
Ok i will try and tell you if it work, thank
@Plague Yes
Checkered GiantOP
i try creating the action.ts :
'use server';

import { cookies } from 'next/headers'

async function test() {

    cookies().set('name', 'value')

    let data = "test"
    
    return data
}

export { test }

and i got the error : Cookies can only be modified in a Server Action or Route Handler.
when i try to use the function in my page.tsx, do you have an idea of why?
Let me see your page.tsx where you're calling it.
Checkered GiantOP
and when i call it in my api i dont got any error but the cookies is not set
to try in page i import the func :
import { test } from '../utils/action'

and i call it in a async func as :
let data = await test()
console.log(data)

but i got the error : "Cookies can only be modified in a Server Action or Route Handler"
@Plague
and if i try in my api file as :
'use server';

import { NextApiRequest, NextApiResponse } from 'next'
import { NextResponse } from "next/server";
import type { NextRequest } from 'next/server';
import { test } from '../../../../utils/action'

export async function GET(request:NextRequest) {
    let data = await test()
    
    let response = NextResponse.json({
        status:'succes',
        user:'test',
        data:data,
    },{ status: 200 })  
    
    return response
}

and i call it in my page with :
const res = await fetch("http://localhost:3000/api/user/cookiestest", {
  method: "GET",
});
    
const status = res.status
const json = await res.json();
console.log(status,json)
i get my data but not my cookie
Wait if you're doing all this from a server component why not just set the cookie in the server component?
Checkered GiantOP
in my api?
i tell you i allready try but i got an error : "Cookies can only be modified in a Server Action or Route Handler"
No in the server component, you don't need an API route or a server action if you're going to be calling this from a server component, you can just set it directly.]
Checkered GiantOP
how?
if i try to set my cookies in my api or my page.tsx i got the error :
Cookies can only be modified in a Server Action or Route Handler
Right sorry, you can't set them in Server Components, but, you can't call your API route from a server component, that will fail in build. The server action however should work. I don't know why you're receiving an error for that.
if someone have an ideo of how to do it, an "example" website with cookies or any other information/resource to help please tell me ^^
Eric just answered in other thread
@Ray Eric just answered in other thread
Checkered GiantOP
oh thanks!
@Ray Eric just answered in other thread
Checkered GiantOP
he tell why it is not working but not how to make it work so i send him a message, thanks you
well he has already said you have to use the server action with form to set the cookie
Checkered GiantOP
a form to set the cookies?
what do you mean "form"?
import { myAction } from './actions'
 
export default function ClientComponent() {
  return (
    <form action={myAction}>
      <button type="submit">Add to Cart</button>
    </form>
  )
}
Checkered GiantOP
!
ooh god thanks
what is your use case
@Ray what is your use case
Checkered GiantOP
login/register so i need to create the account with my db and set the token as cookies
then just use it with form?
@Ray then just use it with form?
Checkered GiantOP
ok but just a question, if my form action call the action, how can i display an error on the page with the action.ts?
Checkered GiantOP
thanks!
you can use react-hook-form if you want client side validation
just call the action in onSubmit function
Checkered GiantOP
ok i will try and i tell you if i got an error, thanks you