2

Hi I am using Nuxt 3 I am trying to set and get cookie on server/api. I have two pages index.vue and about.vue and two server/api files setcookie.get.js and getcookie.get.js. In the index.vue making request to /api/setcookie on a button click to set cookie. In the about.vue making request to /api/getcookie which will console cookie in terminal. Initially it works fine as you can see cookie in the terminal, also in page navigation you can get the cookie in terminal but when i reload about page cookie becomes empty object as you can see in terminal so My question is how can i get cookie on page reload as well. Please note that i have httpOnly true and httpOnly false and none of them i am getting after reload.

pages/index.vue

<script setup>
async function handleSetCookie() {
  console.log('HandleSetCookie Called');
  const options = {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
    },
  };
  const { data } = await useAsyncData(() => $fetch('/api/setcookie', options));
  if (data) {
    return navigateTo('/about', { replace: true });
  }
}
</script>
<template>
  <h1>Home Page</h1>
  <button @click="handleSetCookie">Set Cookie</button>
</template>

pages/about.vue

<script setup>
const options = {
  method: 'GET',
  headers: {
    'Content-Type': 'application/json',
  },
  credentials: 'include', // with or without doesn't work
};
const { data } = await useAsyncData(() => $fetch('/api/getcookie', options));
</script>
<template>
  <h1>About Page</h1>
</template>

server/api/setcookie.get.js

export default defineEventHandler(async (event) => {
  setCookie(event, 'accessToken', '34accesstoken123456', {
    sameSite: 'strict',
  });
  setCookie(event, 'refreshToken', '12refreshtoken123456', {
    sameSite: 'strict',
    httpOnly: true,
  });
  return { msg: 'setting cookie' };
});

server/api/getcookie.get.js

export default defineEventHandler(async (event) => {
  const cookies = parseCookies(event);
  console.log('Hello Cookies', cookies);
  // console.log(event.node.req.headers.cookie);
  return { msg: 'getting cookie' };
});

Terminal Output

Johnny
  • 21
  • 3

0 Answers0