Set Cookies in NextJS 13.4 doesnt work (for me)

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.

const setSessionToken = () => {
  const options = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    }, 
    body: JSON.stringify({sessionToken: uuidv4()}),
  };

  fetch("http://localhost:3000/api/setcookies", options)


};

setSessionToken();

I’m hoping someone can helpe me or point out what might be going wrong with my code. Thanks in advance for the help

You want NextResponse from next/server

2 Likes

Thanks, but still doesn’t work :dizzy_face:

I tried the API endpoint in Postman, where I received the cookies. However, I can’t seem to find them in the Chrome DevTools.

Are you saying it works in Postman but not the browser or are you expecting the cookie to be in the browser when using Postman?

How are you testing sending the POST in the browser?

1 Like

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

Thats my fetch function:

const setSessionToken = () => {
  const options = {
    method: 'POST',
   
    credentials: 'include',
    headers: {
      'Content-Type': 'application/json'
    }, 
    // body: JSON.stringify({sessionToken: uuidv4()}),
  };

  fetch("http://localhost:3000/api/setcookies", options)
  .then((response) => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json(); // Parse the JSON response
  })
  .then((data) => {
    console.log(data);
  })
  .catch((error) => {
    console.error('Fetch error:', error);
  });

};

Is the POST code the same as before just with the import fixed?

The code you have posted so far works for me. Try it in an incognito window to make sure no extensions are running and blocking it.


I’d suggest creating a repo for it and share that.

1 Like

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.

1 Like

Yep, the only thing I changed is the import and after that I started to receive the cookies in Postman.

I also tried the inkognito mode, Firefox and the Edge Browser.

I try out some stuff tomorrow, maybe start a new clean project in a VM

Oh man ‘use client’ did it for me
I could cry :sweat_smile:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.