authjs-nuxt icon indicating copy to clipboard operation
authjs-nuxt copied to clipboard

updateSession doesn't persist the new session

Open Hebilicious opened this issue 1 year ago • 1 comments

Discussed in https://github.com/Hebilicious/authjs-nuxt/discussions/123

Originally posted by miguelakira October 26, 2023 I tried using updateSession to update the session with an arbitrary data. It works, but when I call the session object again somewhere else, it no longer contains the updated data.

const { session, updateSession } = useAuth()
await updateSession((session: Session) => {
    return { ...session, newData: 'something' };
});

and somewhere else, const { session } = useAuth() will give me the session without newData

Hebilicious avatar Oct 30 '23 10:10 Hebilicious

I had the same problem, I think it's because only the store is updated and after making any other actions the Auth session callback updates the session store from the cookies.

const session = useState("auth:session", () => null);
  const cookies = useState("auth:cookies", () => ({}));
  const status = useState("auth:session:status", () => "unauthenticated");
  const sessionToken = computed(() => cookies.value?.["next-auth.session-token"] ?? "");
  const user = computed(() => session.value?.user ?? null);
  watch(session, (newSession) => {
    if (newSession === null)
      return status.value = "unauthenticated";
    if (Object.keys(newSession).length)
      return status.value = "authenticated";
  });
  const updateSession = (u) => {
    session.value = typeof u === "function" ? produce(session.value, u) : u;
  };
  const removeSession = () => {
    cookies.value = null;
    updateSession(null);
  };

As a workaround I used removeSession, and signIn again in order to get updated data from provider

DarkLink13 avatar Nov 02 '23 18:11 DarkLink13