8

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.

1
  • It may be helpful to post the code snippet that's giving you trouble. May 17 at 17:28

3 Answers 3

16

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();
}
2
  • 2
    You can avoid doing the getAll and mapping it after, just cookies().toString() will do the trick. Jun 16 at 20:21
  • 1
    @JeanWalrave, thank you! Jun 23 at 13:29
1

In Next.js 13, for authorization purposes, it's advised to use both Sessions and Cookies. Relying solely on Cookies is insufficient, especially when managing server-side processes.

For instance, consider you're trying to fetch data from a server-side component like this:

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

While you can read the cookies in the API_ENDPOINT, modifying them directly here may not reflect on the client side. As an example, if you're trying to regenerate a token in the API_ENDPOINT using:

const response = NextResponse.next();
response.cookies.set({
    secure: process.env.NODE_ENV === "production",
    name: JWT_NAME,
    value: "New Token",
    httpOnly: true,
    maxAge: 5000,
    path: '/',
});
return response;

The changes you make to the cookies won't be reflected in the browser, because the response here is sent back to the server and not directly to the browser.

In such scenarios, it's beneficial to use sessions in the same manner as libraries like next-auth do.

0

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 } };
}

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.