Next.js Discord

Discord Forum

Fetching Sessions results in error

Answered
Northeast Congo Lion posted this in #help-forum
Open in Discord
Northeast Congo LionOP
Hello! I am trying to fetch users from my database depending on theri session and the email attatched to it. However I have an issue. When I am fetching my users it turns out that i am always catching an error and returning null. The error states that it has something to do with headers but I am unsure what that has to do with finding sessions and the getServerSession functions. the following files are my getSession file which I am using to fetch the session, a getCurrentUser which is what is failing, and a async component Sidebar where I need to fetch the current user from.
import { getServerSession } from "next-auth";
import { authOptions } from "../api/auth/[...nextauth]/route";

export default async function getSession() {
    return await getServerSession(authOptions);
}


import prisma from "../libs/prismadb";
import getSession from "./getSession";

const getCurrentUser = async () => {
    try {
        const session = await getSession();
        if (!session?.user?.email) {
            return null;
        }
        

        const currentUser = await prisma.user.findUnique({
            where: {
                email: session.user.email as string
            }
        });

        if (!currentUser) {
            return null;
        }

        return currentUser;

    } catch (error: any) {
        console.error("An error occurred:", error);
        return null;
    }
}

export default getCurrentUser;

I am attempting to use these actions in my async function called navbar. It is not a client component.
import getCurrentUser from '../../actions/getCurrentUser';
import DesktopSidebar from './sidebar/DesktopSidebar';


export async function MainNav(){
  const currentUser = await getCurrentUser();
  console.log("CURR USER: ", currentUser);

  return (
    <DesktopSidebar currentUser={currentUser!}/>
  );
}


Attempted Solutions:

I have tried putting "use server" at the top, but these are server actions and cant be used with component.
Answered by Ray
"use client";

import { AppShell } from "@mantine/core";
import { useDisclosure } from "@mantine/hooks";
import { MainHeader } from "./header";
import { ReactNode } from "react";

export function CollapseDesktop({
  children,
  mainNav,
}: {
  children: ReactNode;
  mainNav: ReactNode;
}) {
  const [mobileOpened, { toggle: toggleMobile }] = useDisclosure();
  const [desktopOpened, { toggle: toggleDesktop }] = useDisclosure(true);

  return (
    <AppShell
      header={{ height: 60 }}
      navbar={{
        width: 300,
        breakpoint: "sm",
        collapsed: { mobile: !mobileOpened, desktop: !desktopOpened },
      }}
      padding="md"
    >
      <MainHeader
        mobileOpened={mobileOpened}
        toggleMobile={toggleMobile}
        desktopOpened={desktopOpened}
        toggleDesktop={toggleDesktop}
      />

      {mainNav}

      <AppShell.Main>{children}</AppShell.Main>
    </AppShell>
  );
}

// layout.tsx
import { MainNav } from './navbar';

export default function Layout({children}:{children:ReactNode}) {
    return (
        <CollapseDesktop mainNav={<MainNav />}>
            {children}
        </CollapseDesktop>
    )
}
View full answer

62 Replies

@Northeast Congo Lion Hello! I am trying to fetch users from my database depending on theri session and the email attatched to it. However I have an issue. When I am fetching my users it turns out that i am always catching an error and returning null. The error states that it has something to do with headers but I am unsure what that has to do with finding sessions and the getServerSession functions. the following files are my getSession file which I am using to fetch the session, a getCurrentUser which is what is failing, and a async component Sidebar where I need to fetch the current user from. import { getServerSession } from "next-auth"; import { authOptions } from "../api/auth/[...nextauth]/route"; export default async function getSession() { return await getServerSession(authOptions); } import prisma from "../libs/prismadb"; import getSession from "./getSession"; const getCurrentUser = async () => { try { const session = await getSession(); if (!session?.user?.email) { return null; } const currentUser = await prisma.user.findUnique({ where: { email: session.user.email as string } }); if (!currentUser) { return null; } return currentUser; } catch (error: any) { console.error("An error occurred:", error); return null; } } export default getCurrentUser; I am attempting to use these actions in my async function called navbar. It is not a client component. import getCurrentUser from '../../actions/getCurrentUser'; import DesktopSidebar from './sidebar/DesktopSidebar'; export async function MainNav(){ const currentUser = await getCurrentUser(); console.log("CURR USER: ", currentUser); return ( <DesktopSidebar currentUser={currentUser!}/> ); } Attempted Solutions: I have tried putting "use server" at the top, but these are server actions and cant be used with component.
where do you render <MainNav />?
Northeast Congo LionOP
i render it in my layout.tsx file
let me pull it up
import { CollapseDesktop } from "../(site)/components/collapsable-desktop";


export default async function HomeLayout({
children
}: {
children: React.ReactNode;
}) {

return (
<CollapseDesktop children={children}>
</CollapseDesktop>
);
};

Ok actually i am using a collapse desktop component in the layout.tsx file. Then in that component I am using main nav. Turns out that it is a client

'use client';

import { AppShell} from '@mantine/core';
import { useDisclosure } from '@mantine/hooks';
import { MainHeader } from './header';
import { MainNav } from './navbar';


interface User {
id: string;
name: string;
createdAt: Date;
images: string;
}


export function CollapseDesktop({children}:
{children: any,})
{

const [mobileOpened, { toggle: toggleMobile }] = useDisclosure();
const [desktopOpened, { toggle: toggleDesktop }] = useDisclosure(true);



return (

<AppShell
header={{ height: 60 }}
navbar={{
width: 300,
breakpoint: 'sm',
collapsed: { mobile: !mobileOpened, desktop: !desktopOpened },
}}
padding="md"
>


<MainHeader
mobileOpened={mobileOpened}
toggleMobile={toggleMobile}
desktopOpened={desktopOpened}
toggleDesktop={toggleDesktop}
/>



<MainNav/>


<AppShell.Main>
{children}
</AppShell.Main>
</AppShell>
);
}
Northeast Congo LionOP
oh so its making the sidebar a client and unable to load the session?
@Ray yes
use useSession hook
Northeast Congo LionOP
so in the client use the client useSession hook and modify the find user function so that it fetches user based on that?
instead of the server based one
Northeast Congo LionOP
ty sm!
my bad im kind of new to working with nextjs
but where are you rendering <CollapseDesktop />?
Northeast Congo LionOP
let me check
i have my root layout which is just wrapped in context providers
then i have a users directory/route where users are redirected after they are signed in
Northeast Congo LionOP
and in that layout im putting CollapseDesktop
oh
Northeast Congo LionOP
sorry i mispoke
root layout is server not client
regular layout is also server not client
ok
show the code on the layout
Northeast Congo LionOP
sure
where you rendering CollapseDesktop
Northeast Congo LionOP
Here is the layout

The second image is where im rendering it
in users/layout.tsx
ok cool
@Northeast Congo Lion Here is the layout The second image is where im rendering it
"use client";

import { AppShell } from "@mantine/core";
import { useDisclosure } from "@mantine/hooks";
import { MainHeader } from "./header";
import { ReactNode } from "react";

export function CollapseDesktop({
  children,
  mainNav,
}: {
  children: ReactNode;
  mainNav: ReactNode;
}) {
  const [mobileOpened, { toggle: toggleMobile }] = useDisclosure();
  const [desktopOpened, { toggle: toggleDesktop }] = useDisclosure(true);

  return (
    <AppShell
      header={{ height: 60 }}
      navbar={{
        width: 300,
        breakpoint: "sm",
        collapsed: { mobile: !mobileOpened, desktop: !desktopOpened },
      }}
      padding="md"
    >
      <MainHeader
        mobileOpened={mobileOpened}
        toggleMobile={toggleMobile}
        desktopOpened={desktopOpened}
        toggleDesktop={toggleDesktop}
      />

      {mainNav}

      <AppShell.Main>{children}</AppShell.Main>
    </AppShell>
  );
}

// layout.tsx
import { MainNav } from './navbar';

export default function Layout({children}:{children:ReactNode}) {
    return (
        <CollapseDesktop mainNav={<MainNav />}>
            {children}
        </CollapseDesktop>
    )
}
Answer
Northeast Congo LionOP
unfortunantly collapseabledesktop is a clinet component bc it uses hooks to be responsive
you can render server component through the props of client component
Northeast Congo LionOP
oh wow
i didint know you could do this hold on
Northeast Congo LionOP
running the server
sorry now im getting errors about a different issue
what is the error
Northeast Congo LionOP
it makes sense that to use hooks i need for it to be client. But i cant call client comps from server apparently
try to remove 'use client'
oh you are calling it on server?
Northeast Congo LionOP
you can't use hook on server
where are you using it
Northeast Congo LionOP
i was using it in a desktop Sidebar component
it didint have use client in the top but adding it now
everything works now
let me check about the sesison
cool
Northeast Congo LionOP
yep im able to get the object now!!!!!
thank you sm!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
np
Northeast Congo LionOP
sorry i was goign through a tutorial and they were using tailwind so i got messed up with the client vs server differences. This helps alot ill read the article
how do i resolve an post?
right click a message you want it to be the answer > application > mark solution