I have problems to set cookies, and I’m not sure if I’m missing something or if it’s just a lack of understanding on my part. I would really appreciate some help.
Below is the code I’m currently working with:
import { NextResponse } from 'next/headers';
export async function POST(req, res) {
try {
const body = await req.json();
console.log('body: ', body); // Delete later
const response = NextResponse.json({ message: 'Cookie set successfully' });
response.cookies.set('test', '555', {
httpOnly: false,
path: '/',
});
return response;
} catch (error) { return new Response(error.message, { status: 500 }); } }
On the client side, I’m using fetch to initiate a request to the endpoint
and hand over a token.
If I use Postman, I get the cookies from the endpoint. When I use the fetch function on the client side (by running the function on the landing page), the cookies don’t get set in the browser.
I do receive the ‘Cookie set successfully’ message in the console, indicating that the endpoint is functioning fine
I’m guessing you didn’t mark the client code as such?
At the top of the client component add.
'use client'
I was under the assumption it would give an error without that but I think I added that initially because I was testing it using a click handler and not just a function that is invoked.