atinux / nuxt-auth-utils

Add Authentication to Nuxt applications with secured & sealed cookies sessions.
MIT License
981 stars 91 forks source link

No session when fetching during SSR #97

Closed raggesilver closed 5 months ago

raggesilver commented 5 months ago

I've noticed that $fetching during SSR results in a 401 when calling getUserSession/requireUserSession in the server.

GitHub setup:

import { AUTHORIZED_REDIRECT } from "~/lib/constants";
import { getOrCreateUser } from "~/server/services/user";

export default oauth.githubEventHandler({
  config: {
    emailRequired: true,
  },
  async onSuccess(event, { user: profile }) {
    const user = await getOrCreateUser("github", profile);
    await setUserSession(event, {
      user,
    });
    return sendRedirect(event, AUTHORIZED_REDIRECT);
  },
  // Optional, will return a json error and 401 status code by default
  onError(event, error) {
    console.error("GitHub OAuth error:", error, event);
    return sendRedirect(event, "/");
  },
});

API route setup:

import { getAllWorkspaces } from "~/server/services/workspace";

export default defineEventHandler(async (event) => {
  const session = await getUserSession(event);

  if (!session.user) {
    console.log("No user", JSON.stringify(event.node.req, null, 2));

    throw createError({ status: 401, message: "Unauthorized" });
  }

  return getAllWorkspaces(session.user.id);
});

Use in component:


const client = useQueryClient();
const { data, isLoading } = useQuery(
  {
    queryKey: ["workspaces"],
    queryFn: () =>
      $fetch("/api/workspace").catch((err) => {
        // Prints error in SSR
        console.error(err);
        throw err;
      }),
  },
  client,
);

No error is thrown in the client, and the data is fetched correctly. Erros on the server are only printed once (during SSR). Am I doing something wrong?

Package versions ``` nuxt-auth-utils@0.0.25 nuxt@3.11.2 nitropack@2.9.6 h3@1.11.1 node: v21.7.3 ```

Full repo.

atinux commented 5 months ago

@raggesilver could you try with useRequestFest() instead?

See more context in https://github.com/nuxt/nuxt/issues/24813

raggesilver commented 5 months ago

That works! I take it from the issue you linked this is a bug in Nuxt, right? If not, it would be good to have this in the README.

Thanks

atinux commented 5 months ago

It's not directly a bug but something we can improve in Nuxt for the long term.

Would you be happy to help me improve this readme to explain the usage of useRequestFetch() for this module?

raggesilver commented 5 months ago

For sure! I'll open a PR tomorrow.