Next-auth redirects me back to dashboard after logout
Asked Answered
T

3

6

I have a credential based auth flow in NextJS and a dashboard page I have also created custom AccessDenied component in case it not logged used would end up on the dashboard route, hence I did not set redirect in the getServerSideProps where I fetch the data. so my checkout handler looks like so

    onClick={() => {
            signOut();
            router.push("/");
          }}

but after I end up on the index page after a short while i am redirecte to the dashboard page, I don'tt understand why

This is my dashboard page

const DashboardPage = ({
  sessionData,
}: InferGetServerSidePropsType<typeof getServerSideProps>) => {
  const [renderedInfo, setRenderedInfo] = useState<RenderedInfo>();
  const matches = useMediaQuery("(max-width: 768px)");

  useEffect(() => {
    if (!matches) setRenderedInfo("UserDetails");
  }, [matches]);

  if (!sessionData) {
    return <AccessDenied />;
  }

  const { address, userEmail, avatar } = sessionData;
  const menuPanelVisible = !matches || (matches && !renderedInfo);
  const userDisplayName = address?.length ? address[0] : userEmail;
  return (
    <div className="flex-1 px-4 flex w-full justify-center">
      {menuPanelVisible && (
        <MenuPanel>
          <UserAvatar avatar={avatar} displayName={userDisplayName} />
          <DashboardNavigation setRenderedInfo={setRenderedInfo} />
        </MenuPanel>
      )}
      <InformationPanel
        renderedInfo={renderedInfo}
        setRenderedInfo={setRenderedInfo}
        address={address}
      />
    </div>
  );
};

export default DashboardPage;

interface GetServerSidePropsType {
  sessionData?: {
    address: string[] | undefined;
    avatar:
      | {
          url: string;
          width?: number | null | undefined;
          height?: number | null | undefined;
        }
      | null
      | undefined;
    userEmail: string;
  } | null;
}

export const getServerSideProps: GetServerSideProps<
  GetServerSidePropsType
> = async (context) => {
  const session = await unstable_getServerSession(
    context.req,
    context.res,
    authOptions
  );

  console.log({ email: session?.user.email });

  if (!session?.user.email) {
    return {
      props: {
        session: null,
      },
    };
  }

  const { data } = await personAuthApolloClient.query<
    GetPersonDetailsByEmailQuery,
    GetPersonDetailsByEmailQueryVariables
  >({
    query: GetPersonDetailsByEmailDocument,
    variables: {
      email: session.user.email,
    },
  });

  const address = data.person?.address;
  const avatar = data.person?.avatar;
  const sessionData = { address, avatar, userEmail: session.user.email };

  return {
    props: { sessionData },
  };
};

What do I need to do to stay on the index page after redirect on logout?

Thanks

Teaching answered 6/8, 2022 at 11:39 Comment(2)
Hi Seven, can you share the signOut function implementation? And can you log the sessionData prop value before and after a user has been logged out?Overstuff
hi @Christopher Reece thanks, you are right, it was undefined after logout there was another call to getServerSide props so that answers why, and how is signOut is a function provided by next-auth i did not implement it but it accepts params so this was solved this way: onClick={() => { signOut({ redirect: true, callbackUrl: process.env.NEXT_PUBLIC_BASE_URL, }); }}Teaching
L
14

This is the correct way to Signout and redirect to a specific url

 signOut({ callbackUrl: 'http://localhost:3000/foo' })

If you need to redirect to a another website you can do it by modifying the callbacks object in [...nextauth.ts] file like this

  callbacks: {
   async redirect({ url, baseUrl }) {
    //this is the default behavior
    // Allows relative callback URLs
    if (url.startsWith("/")) return `${baseUrl}${url}`
    // Allows callback URLs on the same origin
    else if (new URL(url).origin === baseUrl) return url
    return baseUrl
   //Youcan add and modify it your usecase here
  }
}
Lustrous answered 17/5, 2023 at 9:12 Comment(2)
thank you, I was about to throw myself off a bridge.Tham
I initially had a mildly hard time finding this but here's the documentation from Next Auth for more deets: next-auth.js.org/getting-started/client#signoutAvan
O
5

try this it might help you

onClick={() => {
    signOut({ redirect: false }).then(() => {
        router.push("/"); // Redirect to the dashboard page after signing out
    });
}}
Outface answered 23/8, 2023 at 18:21 Comment(1)
I love this, it brings out the all thing in a very easy and wonderful wayWarhead
M
2

This is because next auth didn't make signout correctly and it still thinks that your session is valid, if U want correctly make signOut from a session U would need to provide callback Url in your signOut function like signOut({ callbackUrl: your-provider-id }), where callbackUrl must be id of your current provider, U can take this provider from a session object

Medicine answered 29/11, 2022 at 18:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.