Search code examples
reactjsnext.jsfetch-api

Next.js does not send cookies with fetch request even though credentials are included


I'm working on a Next.js application which was originally a normal react app (created with create-react-app) and I am trying to send cookies with a fetch request to my server. However, the cookies aren't being sent even though I've set credentials: 'include' in my fetch options.

The exact same code is working in the "not" Next js app.

I also included the "use client" option. The files are in the new "app" folder from next version 13.

UPDATE 1: Here is some code I used:

async function getToken() {
  const res = await fetch(
    'http://localhost:8080/api/auth/token', {
      credentials: 'include'
    }
  );
  if (!res.ok) {
    return null;
  }
  return res.json();
}

export default async function Component({
  children
}) {

  const tokenData = getToken();
  const token = await tokenData;

  /* some other code */

  return {
    children
  }
}

UPDATE 2: Based on the input from edgefish and further experimentation, I acknowledge that in versions of Next.js up to 12, methods such as getServerSideProps could be used. However, since the introduction of the "app" folder in Next.js 13, these methods no longer function within the "app" folder itself (refer to this link). I'm curious to know if there is a way to incorporate cookies into a fetch request in Next.js 13 using a server-side component. While it's possible to retrieve the client-sent cookie using the cookies method (see this link), I'm unsure how to include that cookie in the subsequent fetch request. Note that using credentials: 'include' is ineffective as long as the component is a server component.


Solution

  • To include cookies in Next 13 server-side fetch:

    1. Read the request cookies with the cookies function

    2. Add Cookie header to the server-side fetch request

    import { cookies } from "next/headers";
    
    async function getData() {
      const response = await fetch(process.env.API_ENDPOINT, {
        headers: { Cookie: cookies().toString() },
      });
      return await response.json();
    }