0

Consider the following code

Index.getInitialProps = async function({req}) {
  const res = await fetch("http://localhost/api/tiles");
  const json = await res.json();
}

Suppose the /api/tiles endpoint needs access to the uid cookie on the user. Normally, one would do {credentials: "include"}. But how do I do this in Next.js?

Trect
  • 2,759
  • 2
  • 30
  • 35
kahoha
  • 45
  • 1
  • 5

4 Answers4

1

You can try this

const options = {
  method: "POST",
  credentials: 'include',
  headers: {
    "Content-Type": "application/json",
    "Cookie": "access-token=YOUR-TOKEN;path=/;expires=Session" 
  },
  body: JSON.stringify({}),
  cache: "no-store",
};

fetch("YOUR-URL", options).then(response => response.json().then(data => console.log(data)));

Hope this helps

Nazim.A
  • 101
  • 1
  • 4
0

As you are using React (NextJS is built on ReactJS) you can use react-cookie to get and cookies that are stored in the system.

Install react-cookie

npm install react-cookie

If you are using Reactjs with version >= 16.8.0 you can use React hooks.

const [cookies, setCookie, removeCookie] = useCookies(['cookie-name']);

You can set cookie with setCookie(name, value, [options]) and get the cookies with cookie.get(name, [options])

So in your case the code should look like

import { useCookies } from 'react-cookie';
const [cookies, setCookie] = useCookies(['name']);

Index.getInitialProps = async functon({req}) {
  cookie = cookies.get(name)
  const res = await fetch("http://localhost/api/tiles", cookie);
  const json = await res.json();
}
Trect
  • 2,759
  • 2
  • 30
  • 35
  • Absolutely no reason you need to install an external library for this, let alone a react-specific library. This should not be marked as the correct answer. – Jeremy Bernier Jul 06 '23 at 07:30
0

If you are using over v13.4.0, there are 2 ways to include cookies for frontend fetching and backend fetching.

const res = await fetch('/url', {credentials: 'include'})
import {cookies} from 'next/headers';

const getCookie = async (name: string) => {
    return cookies().get(name)?.value ?? '';
}

const cookie = await getCookie('cookie-name');

const res = await fetch('/url', {
    headers: {
        Cookie: `cookie-name=${cookie};`
    }
});
0

You absolutely do not need an external library to do this. Also getInitialProps has been deprecated, use getServerSideProps or getStaticProps instead.

On the frontend, setting credentials: "include" in the fetch will pass the cookies, but on the backend this will not forward the client's cookies. In order to do that on the server, you can retrieve the cookies via context.req.headers.cookie and explicitly pass this cookie in the headers object.

The following works:


export const getServerSideProps = async (context) => {
  const { cookie } = context.req.headers;
  const res = await fetch(url,
    {
      credentials: "include",
      headers: { cookie },
    }
  );
  const data = await res.json();
  return {
    props: { data }
  }
}

(obviously you probably want to do some error handling on the fetch, but that's outside the scope of the question)

Jeremy Bernier
  • 1,746
  • 1
  • 17
  • 17