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

112 messages · Page 1 of 1 (latest)

raw emberBOT
#

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

latent veldt
#

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.

wanton lance
#

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”

#

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

latent veldt
#

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.

wanton lance
#

how can i specify and absolute path? I'm not really good in it so sorry. I tried kinda everyting

latent veldt
#

for now, just hard-code it. hastes make wastes.

wanton lance
#

What do you mean by hardcode it?

#

What should i change?

latent veldt
wanton lance
#

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

latent veldt
#

slow down.

#

as i mentioned, you need to isolate the issue, either of fetch or cookie.
for now, forget about cookie. okay?

wanton lance
#

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

latent veldt
#

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

wanton lance
#

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

latent veldt
#

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
    });
}
wanton lance
#

alright

latent veldt
#

then call it witch cURL

curl -I http://your-api-server/api
#

make sure if COOKIE exists in the HTTP response headers.

wanton lance
#

Okay

latent veldt
#

i changed the code a bit.

wanton lance
#

i see

#

The curl doesn’t want to work for sure

latent veldt
#

have u ever used cURL?

wanton lance
#

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
latent veldt
#

what os do u use? mac, win, WSL?

wanton lance
#

windows, with vs code terminal

latent veldt
#

double quote url like
curl -I "http...."

wanton lance
#

alright

latent veldt
#

it is capital i

#

large i

wanton lance
latent veldt
#

can u do that from power shell?

wanton lance
#

yeah

#

the same

latent veldt
#

how about without option like
curl http...

wanton lance
#

curl : The remote server returned an error: (405) Method Not Allowed.
At line:1 char:1

latent veldt
#

oh sorry its POST so
curl -XPOST http...

wanton lance
#

ohh okay

latent veldt
#

good. so
curl -XPOST -I "http...

wanton lance
#

alright

latent veldt
#

now we made sure it returns a cookie header. cookie works fine.

#

so we made sure both fetch and cookie.

wanton lance
#

yeah, thanks

latent veldt
#

so the culprit could be when setting the value to cookie. maybe serializing .

wanton lance
#

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

latent veldt
#

cookies().set("userData", body?.userData || {});
this part, you need to serizalize it with stringfy

wanton lance
#

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,
});
}

latent veldt
#

stringfy userData

#

yeah

wanton lance
#

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

latent veldt
#

sorry. did u change the subject?

wanton lance
#

What do you mean?

latent veldt
#

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,
  });
}
wanton lance
#

no, not working

latent veldt
#

this code works or not

#

can i see the curl response?

wanton lance
#

No respones for this

latent veldt
#

can u add -I option?

wanton lance
#

yeah, anywhere or specific location?

latent veldt
#

curl -XPOST -I -H

wanton lance
latent veldt
#

sorry
-I -X

wanton lance
#

the same

latent veldt
#

curl -I -H

#

u don't need -XPOST

wanton lance
#

still the same

latent veldt
#

curl -v -I 'http...' -H ... -d ...

wanton lance
#

like this?

latent veldt
#

yes

wanton lance
#

the same

latent veldt
#

sorry omit -I
curl -v "http..." -H .. -d ...

wanton lance
latent veldt
#

yeah, so it returns 500. your api failed in the middle of processing.
that is why cookie is not set.

wanton lance
#

what can i do then?

latent veldt
#

do you write codes with JS, not TypeScript btw?

wanton lance
#

JS

latent veldt
#

you might want to use TypeScript, so you can avoid easy mistake such as JSON.Stringfy()

#

TypeScript tells u diff btw Object, array, string

wanton lance
#

yeah i thinked about that but for some reasons i have to stay with JS

latent veldt
#

I greatly reccomend you to use TS.

wanton lance
#

alright, just the main developers at the company uses JS as well so its kinda hard to tell htem to sswitch too

latent veldt
#

even if you fix the issue, you would hit another issue, then come back here again. i bet.

wanton lance
#

yeah maybe u are right

#

i will tell to the devs that

#

but now i have to fix tthis issue somehow i njs

latent veldt
#

maybe you wrap it up this thread. then create a new one.

wanton lance
#

okay, i will maybe someone faced with this issue as well

#

thanks for your help!