Next.js 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();
});
});
};