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?
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};`
}
});
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With