skip to Main Content

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.

2

Answers


  1. If you wenna send credentials of fetch in nextjs project,
    You must use Client-side Rendering (CSR)

    import useSWR from 'swr';
    
    const fetcher = (url: string) => fetch(url).then((res) => res.json());
    const YourPage = () => {
      const { data, error, isLoading } = useSWR(`https://.../data`, fetcher);
    
       return (
         <div>{JSON.stringify(data)}</div>
       );
    
    };
    

    OR

    If you wenna Server-side Rendering (SSR).

    You can using the getServerSideProps in nextjs project, You can like…

    import type { GetServerSidePropsContext } from 'next';
    
    export async function getServerSideProps(context: GetServerSidePropsContext) {
      const { cookie } = context.req.headers;
    
      // Fetch data from external API
      const res = await fetch(`https://.../data`, {
        headers: { Cookie: cookie },
      });
    
      const data = await res.json();
    
      // Pass data to the page
      return { props: { data } };
    }
    
    
    Login or Signup to reply.
  2. 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()
            .getAll()
            .map(({ name, value }) => `${name}=${value}`)
            .join("; "),
        },
      });
      return await response.json();
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search