Skip to content

No session when fetching during SSR #97

@raggesilver

Description

@raggesilver

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

Full repo.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions