how do i send httponly cookie with fetch request in nextjs

32 views Asked by At

I've completed a guide and now aim to retrieve user details using a server component. However, despite the cookie being present in the browser, it doesn't seem to appear in the request.

I customized my profile page and transformed it into a server component. However, upon reloading the page to initiate the fetch request, the token cookie is absent. I've verified this using the following lines of code within the route handler:

const token = request.cookies.get("token")?.value || "";
console.log(token, "token");
1

There are 1 answers

2
Tanishq S On

If you are using NextJS, it is best to use the cookies-next library https://www.npmjs.com/package/cookies-next

Try this:

setCookie('cookie_name', cookie_value, { httpOnly: true })

For fetch request,

useEffect(() => {
    const setCookie = async () => {
      try {
        const response = await fetch('/api/set-cookie', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ cookieName: 'myCookie', cookieValue: 'cookieValue' })
        });

        if (response.ok) {
          console.log('Cookie set successfully');
        } else {
          console.error('Failed to set cookie');
        }
      } catch (error) {
        console.error('Error setting cookie:', error);
      }
    };

    setCookie();
  }, []);

Without using a library:

const [cookies, setCookie] = useCookies(['token']);

  useEffect(() => {
    // Assuming 'token' is obtained from somewhere
    const token = 'your_token_value';

    // Setting the 'token' cookie with the provided value and options
    setCookie('token', token, {
      httpOnly: true,
    });
  }, []);