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:
-> I googled how to ignore that warning via chrome options but I can't find any option. the warning
-> 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.
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?