Next.js Discord

Discord Forum

cookies().set(name, value) not working

Unanswered
Weevil parasitoid posted this in #help-forum
Open in Discord
Original message was deleted.

112 Replies

you might want to isolate the issue, either of cookie or request.json() by

console.log(body?.userData)
cookies().set("userData", 'abc')


as such we can nail down the issue.
having said that, cookie part seems ok.
plus, call the api directly by cURL. it helps a lot.
Weevil parasitoid
I tried it. The console.log shows me that the date transfered correctly. I also tried to set the cookie to a string but nothing
Also tried to use try catch but nothing…
I also set the selected language to a cookie and that’s works fine.

But for the user data I cant call the api without the “localhost:3000”
Weevil parasitoid
So for example this code work fine without the localhost:3000 prefix:
const setSelectedLanguageCookie = (selectedLanguage) => { fetch("/api/settings/language", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ selectedLanguage }), }) .then((response) => response.json()) .then() .catch((error) => console.error(error)); };

but the userData api doesnt work without the prefix cause it says that this is a bad route

await fetch(process.env.URL + "/api/user", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ userData: data.data }), }) .then((res) => res.json()) .then((data) => { if (data.success) { console.log("User data saved"); } else { console.log("User data save error"); } }) .catch((e) => { console.log(e); });
I think that this makes the problem for sure cause if i try to set the UserData cookie inside the language api then it works but i need it in different file
First off, you must specify an absolute path to fetch() used in server side(Node.js), which is so common mistake that many people make. relative path is not allowed.
on top of that, request.json() parts works fine.

then you need to make sure if this code alone works using cURL

cookies().set("userData", 'abc')


try to isolate the issue, making it simple so you can easialy nail down the culprit.
I would recommend to use debugger as well.
Weevil parasitoid
how can i specify and absolute path? I'm not really good in it so sorry. I tried kinda everyting
for now, just hard-code it. hastes make wastes.
Weevil parasitoid
What do you mean by hardcode it?
What should i change?
Weevil parasitoid
await fetch("http://127.0.0.1:3000/api/user", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ userData: data.data }),
})
.then((res) => res.json())
.then((data) => {
if (data.success) {
console.log("User data saved");
} else {
console.log("User data save error");
}
})
.catch((e) => {
console.log(e);
});
Still not working, doesnt save it to the cookies
slow down.
as i mentioned, you need to isolate the issue, either of fetch or cookie.
for now, forget about cookie. okay?
Weevil parasitoid
Alright, the userData: data.data are forwarded correctly that what i see, and the fetch works fine cause when i fetch in the server side i console.log the call
good boy. now we are on the same page, the fetch works and return a value correctly.
then forget about fetch.
let's work on cookie
Weevil parasitoid
okay okay
import { cookies } from "next/headers";
import { NextResponse } from "next/server";

export async function POST(request) {
const body = await request.json();
try {
cookies().set("userData", "test");
return NextResponse.json({
success: true,
data: { userData: body?.userData || {} },
});
} catch (e) {
console.log(e);
return NextResponse.json({
success: false,
data: { userData: body?.userData },
});
}
}
this is the current servert code
slow down.
hastes make wastes.
first off add this line

export const dynamic = "force-dynamic"

export async function POST(request) {
    cookies().set("userData", "test");

    return NextResponse.json({
      success: true
    });
}
Weevil parasitoid
alright
then call it witch cURL

curl -I http://your-api-server/api
make sure if COOKIE exists in the HTTP response headers.
Weevil parasitoid
Okay
i changed the code a bit.
Weevil parasitoid
i see
The curl doesn’t want to work for sure
have u ever used cURL?
Weevil parasitoid
curl -I http://127.0.0.1:3000/api/user

cmdlet Invoke-WebRequest at command pipeline position 1
Supply values for the following parameters:
Uri: http://127.0.0.1.3000/api/user
curl : Cannot find drive. A drive with the name 'http' does not exist.
At line:1 char:1
+ curl -I http://127.0.0.1:3000/api/user
+ ~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (http:String) [Invoke-WebRequest], Driv
eNotFoundException
+ FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.InvokeWebRe
questCommand
what os do u use? mac, win, WSL?
Weevil parasitoid
windows, with vs code terminal
double quote url like
curl -I "http...."
Weevil parasitoid
alright
it is capital i
large i
Weevil parasitoid
curl -I "http://127.0.0.1:3000/api/user"

after it this ask me for URI
can u do that from power shell?
Weevil parasitoid
yeah
the same
how about without option like
curl http...
Weevil parasitoid
curl : The remote server returned an error: (405) Method Not Allowed.
At line:1 char:1
oh sorry its POST so
curl -XPOST http...
Weevil parasitoid
ohh okay
good. so
curl -XPOST -I "http...
Weevil parasitoid
alright
now we made sure it returns a cookie header. cookie works fine.
so we made sure both fetch and cookie.
Weevil parasitoid
yeah, thanks
so the culprit could be when setting the value to cookie. maybe serializing .
Weevil parasitoid
ahh oaky, im kinda afraid about why, i mean i tried with string so its kinda interesting cause the other cookie set works fine but this one not lol
cookies().set("userData", body?.userData || {});
this part, you need to serizalize it with stringfy
Weevil parasitoid
import { cookies } from "next/headers";
import { NextResponse } from "next/server";
export const dynamic = "force-dynamic";

export async function POST(request) {
const body = await request.json();
cookies().set("userData", JSON.stringify(body?.userData) || "");

return NextResponse.json({
success: true,
});
}
stringfy userData
yeah
Weevil parasitoid
now i log the userData and this one is passed trought correctly, and also tested the stringify with console.log its fine
but when i list the cookies this shows me that the userData is not in there
[
{ name: 'selectedLanguage', value: 'en' },
{
name: 'token',
value: 'XXXXXXX'
}
]
these are the only saved ones
But where is set the selected language there it works fine and there it doesn’t require me to use the ip address. It’s works fine without the local ip
But when I tried to use the selecte language fetch with the local ip then that one’s doesn’t wotked either
sorry. did u change the subject?
Weevil parasitoid
What do you mean?
so i want to see if setting cookie with fetch() using stringfy itself works or not.
export async function POST(request) {
  const body = await request.json();
  cookies().set("userData", JSON.stringify(body?.userData) || "");

  return NextResponse.json({
    success: true,
  });
}
Weevil parasitoid
no, not working
this code works or not
can i see the curl response?
Weevil parasitoid
No respones for this
can u add -I option?
Weevil parasitoid
yeah, anywhere or specific location?
curl -XPOST -I -H
Weevil parasitoid
sorry
-I -X
Weevil parasitoid
the same
curl -I -H
u don't need -XPOST
Weevil parasitoid
still the same
curl -I -H "Content-Type: application/json" -d '{"userData": {"key1": "value1", "key2": "value2"}}' http://127.0.0.1:3000/api/user
curl -v -I 'http...' -H ... -d ...
Weevil parasitoid
curl -v -I "http://127.0.0.1:3000/api/user" -H "Content-Type: application/json" -d '{"userData": {"key1": "value1", "key2": "value2"}}'
like this?
yes
Weevil parasitoid
the same
sorry omit -I
curl -v "http..." -H .. -d ...
Weevil parasitoid
yeah, so it returns 500. your api failed in the middle of processing.
that is why cookie is not set.
Weevil parasitoid
what can i do then?
do you write codes with JS, not TypeScript btw?
Weevil parasitoid
JS
you might want to use TypeScript, so you can avoid easy mistake such as JSON.Stringfy()
TypeScript tells u diff btw Object, array, string
Weevil parasitoid
yeah i thinked about that but for some reasons i have to stay with JS
I greatly reccomend you to use TS.
Weevil parasitoid
alright, just the main developers at the company uses JS as well so its kinda hard to tell htem to sswitch too
even if you fix the issue, you would hit another issue, then come back here again. i bet.
Weevil parasitoid
yeah maybe u are right
i will tell to the devs that
but now i have to fix tthis issue somehow i njs
maybe you wrap it up this thread. then create a new one.
Weevil parasitoid
okay, i will maybe someone faced with this issue as well
thanks for your help!
np