#Next Api Route Cookie handling

3 messages · Page 1 of 1 (latest)

rose hill
#

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?

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();
});
});
};```

idle voidBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

night rover
#

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