Search code examples
vue.jscookiesnuxt.jssubdomainpinia

Setting Cookies Domain with pinia persisit store on Nuxt 3


I'm setting up SSO login for two apps on the same sub-domain using Nuxt 3 with Pinia and persisting data in cookie storage. The issue is configuring the cookie's domain option so that it's accessible across both apps on different sub-domains.

import { defineStore } from "pinia";


export const useAuthStore = defineStore(
  "auth",
  () => {
  const loggedUser = ref("");
  const hasPin = ref(false);
  const language = ref(window?.navigator?.language);
  const isLoggedIn = computed(() => !!loggedUser.value);
  const refresh_token = computed(() => loggedUser?.value?.jwToken);
  const access_token = computed(() => loggedUser?.value?.jwToken);
  const roles = computed(() => loggedUser?.value?.roles);
  const userId = computed(() => loggedUser?.value?.id);
  const businessId = computed(() => loggedUser?.value?.businessId);
  const userInfo = computed(() => loggedUser?.value);

function setLoggedUser(data) {
  loggedUser.value = data;
  cookie.value = data
}

function setHasPin(data) {
  hasPin.value = data;
}

function setAccessToken(value) {
  let userInfo = { ...loggedUser?.value, access_token: value };
  setLoggedUser(userInfo);
}
function setRefreshToken(value) {
  let userInfo = { ...loggedUser?.value, refresh_token: value };
  setLoggedUser(userInfo);
}
function updateUser(value) {
  let userInfo = { ...loggedUser?.value, fullName: value };
  setLoggedUser(userInfo);
}
function updateAccountType(value) {
  let userInfo = { ...loggedUser?.value, accountType: value };

  setLoggedUser(userInfo);
}
function updateUserInfo(data) {
  let userInfo = { ...loggedUser?.value, ...data };
  setLoggedUser(userInfo);
}

const logOut = () => {
  const authCookie = useCookie('auth')
  localStorage.clear();
  authCookie.value = null
  window.location.href = "/auth/login";
};
return {
  updateUser,
  isLoggedIn,
  refresh_token,
  access_token,
  roles,
  userId,
  userInfo,
  setRefreshToken,
  setAccessToken,
  updateAccountType,
  updateUserInfo,
  setLoggedUser,
  logOut,
  loggedUser,
  businessId,
  language,
  setHasPin,
  hasPin,
};
 },
{
  persist: {
  storage: persistedState.cookies,
   },
  }
);

I added the code to my auth store setup, at the bottom you can see where i specified cookie as the storage option


Solution

  • Considering that cookies is a wrapper for Nuxt useCookies in the latest version of pinia-plugin-persistedstate, domain option needs to be passed with . prefix in order to apply a cookie to a domain and its subdomains:

    {
      persist: {
        storage: persistedState.cookies({ domain: '.mydomain.com' })
      },
    }
    

    In earlier plugin versions cookiesWithOptions is used instead of cookies for the same purpose.