vue.jscookiesvuejs3

Is there any way to get stored cookies from a different domain?


I'm developing frontend with vuejs and backend with nestjs. I'm hosting frontend at localhost and hosting backend at another domain (so called "example.com"). So vuejs is running on "localhost:5173" and backend is running on "example.com".

My backend sends authorization information with set-cookie header in response to client.

Here is the problem. Client (chrome) received response with set-cookie header (domain attribute is "example.com") and store these cookies in "example.com".

The cookies are available in the browser but I can't access it from vue because it only gets cookies that are stored for "localhost" domain.

Here's my code:

<template></template>

<script setup lang="ts">
import { Account } from './types';

definePage({
  meta: {
    layout: 'blank',
    isLoginProcess: true,
  },
});

const router = useRouter();
const route = useRoute();
const userStore = useUserStore();

const accessToken = useCookie('accessToken').value;
if (accessToken) {
  userStore.accessToken = accessToken;
  useCookie('accessToken').value = null;
}
const account = useCookie<Account>('account').value;
if (account) {
  userStore.account = JSON.parse(JSON.stringify(account));
  useCookie('account').value = null;
}

if (route.query?.route) {
  router.push(`${route.query?.route}`);
} else {
  router.push('/');
}
</script>

How to get the cookies in frontend (vuejs) in a different domain?

Two possible approaches that came to my mind are:

  1. Find a way to force the backend to change the domain to localhost so that the browser saves the cookies even if the request's Host URL and the Domain value are different.

-> I googled how to ignore that warning via chrome options but I can't find any option. the warning

  1. Find a way to fetch cookies registered under example.com from the frontend, rather than using localhost.

-> I'm using vuejs. And use "useCookie" to get the cookie in browser. But it only can get the cookies with same domain (localhost). so I can't find way to get stored cookies with "example.com" as domain.


Solution

  • As deceze mentioned in the comments, you can't access cookies from different domains. You can update the authentication endpoint to return the accessToken in the response body. Then you can store it using useUserStore.

    But be aware that if you want to store the auth data in the local storage, it can be vulnerable to cross-site scripting (XSS) attacks.

    See this question for more information: Where to store a JWT token properly and safely in a web based application?