Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include cookies with fetch request in Nextjs

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?

like image 238
kahoha Avatar asked Jan 24 '26 20:01

kahoha


2 Answers

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};`
    }
});
like image 116
HC0215 Avatar answered Jan 26 '26 10:01

HC0215


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

like image 27
Nazim.A Avatar answered Jan 26 '26 08:01

Nazim.A



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!