Next.js Discord

Discord Forum

Simplifying User Checks (Auth) in App Router

Unanswered
Rat Terrier posted this in #help-forum
Open in Discord
Rat TerrierOP
Hello, I have got next-auth working, but I'm not quite sure that doing this in every route is really a smart idea in each page (a server component):
  const session = await getServerSession(authOptions);

  // Requires a session
  if (!session) {
    return redirect("/");
  }

  // Give the user
  const user = await prisma.user.findFirst({
    where: {
      id: session.user.id,
    },
  });

  // Invalid user stored in session
  if (!user) {
    signOut();
    return redirect("/");
  }


Is there something better I could do?

22 Replies

If you are only checking if there's a active session and user exists in database, do it in middleware and add all those paths to the matcher you want to protect.
Is that possible?
So that I don't call getServerSession() twice
Like is there a way to pass props like how you do in "getServerSideProps" but instead for multiple pages or something?
Or am I out of luck
then yea u need to declare on each pages in which u want to access user.
or u could make a context and hook to access the user on pages u want
but that requires u to mark such page as client component
Rat TerrierOP
Context is only client side so I don't want that
like how u are doing currently
thats the only way
Rat TerrierOP
oh okay
are you sure?
the best i know currently.
Rat TerrierOP
because then on each page I have to check:
const session = getServerSession();

if (!session) {
  return someError;
}
Since session could be null (typescript stuff)
wait for someone to give their thoughts
@Rat Terrier Since session could be null (typescript stuff)
yea my current implement is to return a jsx if session is not there. then check if user exists, then return the actual content
tho u could also use middleware anyway to properly ensure only logged in users are able to access the page
non-logged in users gets redirected if they even try