Next.js Discord

Discord Forum

how to set server-side Cookie?

Unanswered
Atlantic mackerel posted this in #help-forum
Open in Discord
Atlantic mackerelOP
Hey guys, Im trying to add cookie when the user authorization

I tried this:

export async function GET(req: NextRequest) {
    const res = new NextResponse();

    console.log(req.cookies.get("test"))

  return res;
}

export async function POST(req: NextRequest, res: NextResponse) {
    cookies().set('name', 'test')
    const test = undefined;
    req.json().then(value => {
        console.log(value)


    })

    req.cookies.set("test","asdf");

    console.log(req.cookies.get("test"))
    return NextResponse.json({message: "Hello World"});
}


but the cookie on GET method always return undefined how can I fix this?

(or, is there any other way to add custom cookie via Next-Auth like generate uuid)?

+ I also tried cookies().set('name', 'test') but it's return undefined too

2 Replies

Toyger
first of all
 req.cookies.set("test","asdf");

you set cookies on request, it doesn't make sense

you need to set it as you did above
cookies().set('name', 'test')

you just set here name instead test key

and this
console.log(req.cookies.get("test"))

will never show you value, because cookies will be set only when user will get response, and you can read it only on next request
for example as you did in here
export async function GET(req: NextRequest) {