Next Api Route Cookie handling
Unanswered
American black bear posted this in #help-forum
American black bearOP
Hi all,
i have an express server backend that sets httpOnly cookie on the client on login. I want to use these httpOnly cookies to authenticate my fetch requests to the backend .. i dont want to use Bearer=token because that means i would have to store the accessToken inside localStorage what i want to prevent.
So setting the cookies for refresh and access token works finde .. but using them in the api route handlers not. the req.headers.cookie is undefined, though the cookies are available in the client. How can i access them?
and this is the call from the frontend:
i have an express server backend that sets httpOnly cookie on the client on login. I want to use these httpOnly cookies to authenticate my fetch requests to the backend .. i dont want to use Bearer=token because that means i would have to store the accessToken inside localStorage what i want to prevent.
So setting the cookies for refresh and access token works finde .. but using them in the api route handlers not. the req.headers.cookie is undefined, though the cookies are available in the client. How can i access them?
export async function POST(req: NextApiRequest, res: NextApiResponse) {
const cookies = req.headers.cookie;
console.log({ cookies });
try {
const result = await fetch('http://localhost:8080/logout', {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
Cookie: cookies || '',
},
});
const data = await result.json().then((data) => data);
return Response.json({ ok: true, response: { data } });
} catch {
return Response.json({ ok: false });
}
}and this is the call from the frontend:
const handleLogout = async () => {
await fetch('/api/logout', {
credentials: 'include',
method: 'POST',
}).then((res: any) => {
res.json().then((data: any) => {
router.push('/login');
socket.disconnect();
});
});
};2 Replies
i have used cookies from
next/headers like normal page in route handler and its worked nicely in route handler, but is the cookie for a specific path or smth weird@American black bear also after looking at your code, you are not using the right code, for example there is no
also here is the docs on better suggested methods of getting headers: https://nextjs.org/docs/app/building-your-application/routing/route-handlers#headers (ie next/headers [which can be used with cookies](https://nextjs.org/docs/app/api-reference/functions/cookies))
res in app dir, and req is a different type to that...also here is the docs on better suggested methods of getting headers: https://nextjs.org/docs/app/building-your-application/routing/route-handlers#headers (ie next/headers [which can be used with cookies](https://nextjs.org/docs/app/api-reference/functions/cookies))