Search code examples
nuxt.jsnuxtjs3nuxt3

Nuxt3 server setCookie - cookie value does not change, what could be problem?


There is such an implementation of proxying requests to api, for reasons unknown to me, the value of the cookie that comes in the response does not change, but its parameters (for example httpOnly) change.

import { joinURL } from 'ufo';
import { parse as parseCookies } from 'set-cookie-parser';

export default defineEventHandler((event) => {
  const { API_URI } = useRuntimeConfig();
  const path = event.path.replace(/^\/api\//, '');
  const url = joinURL(API_URI, path);

  return proxyRequest(event, url, {
    onResponse(event, response) {
      const combinedCookie = response.headers.get('set-cookie');

      if (combinedCookie) {
        const cookies = parseCookies(combinedCookie);

        cookies.forEach((cookie) => {
          const { name, value, ...options } = cookie;

          console.log('cookie', cookie);

          setCookie(event, name, value, {
            path: options.path,
            expires: options.expires,
            maxAge: options.maxAge,
            domain: options.domain,
            secure: options.secure || false,
            httpOnly: options.httpOnly || false,
          });
        });
      }
    },
  });
});

Solution

  • I solved my problem using this method.

    const event = useRequestEvent();
    
    const res = await $fetch<{ accessToken: string }>('/api/auth/refresh', {
      method: 'POST',
      headers: useRequestHeaders(['cookie']),
      onResponse({ response }) {
        const cookies = response.headers.getSetCookie();
    
        if (cookies.length) {
          cookies.forEach((cookie) => {
            if (event) {
              appendResponseHeader(event, 'set-cookie', cookie);
            }
          });
        }
      },
    });