Next.js Discord

Discord Forum

Errors on server component using nextauth

Unanswered
Sawfly parasitic wasp posted this in #help-forum
Open in Discord
Sawfly parasitic waspOP
I'm trying to make an async server component which depending on the getServerSession from nextauth will render the username, or a login button.
This is my (simplified) component
//components/profile.tsx
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { Suspense } from "react";
import { LoginButton } from "@/components/buttons"; //Client-component

function Profile() {
  return (
    <Suspense fallback={<span>Loading...</span>}>
      <PrivateProfile />
    </Suspense>
  );
}

async function PrivateProfile() {
  const session = await getServerSession(authOptions);
  await new Promise((resolve) => setTimeout(resolve, 2000));
  return session ? <p>{session.user?.name}</p> : <LoginButton />;
}

This code however produces some errors, I could find some other way to do it which wouldn't be SSR, but I'd imagine it should be possible in the way I'm doing. Could somebody explain why this happens and maybe tell if there is a better way to do it?
Errors I'm getting:
Error: Hydration failed because the initial UI does not match what was rendered on the server. Warning: Expected server HTML to contain a matching <button> in <div>. twice
Error: There was an error while hydrating this Suspense boundary. Switched to client rendering.

Sidenotes:
This is a server component
I saw some similar error in another post. It suggested to update to the new next version so I did, nothing changed

1 Reply

Sawfly parasitic waspOP
I solved it by using next/dynamic and setting ssr to false). On the docs it says this is for client components, but it solves it for server components.
I have no idea what it does, but it is still rendered server side, but doesn't throw an error anymore.
docs: https://nextjs.org/docs/app/building-your-application/optimizing/lazy-loading#skipping-ssr
new code:
import dynamic from "next/dynamic";

const Profile = dynamic(() => import("./profile"), {
  ssr: false,
  loading: () => <span>Loading...</span>,
});
export default Profile;