Next.js Discord

Discord Forum

Pass props globally

Answered
Samir posted this in #help-forum
Open in Discord
I have a function to get user from supabase. I want to pass it in all pages.

app/layout.tsx
const getUser = async () => {
  const supabase = createServerComponentClient({ cookies });
  const { data } = await supabase.auth.getUser();

  if (data.user) {
    const userTable = await supabase
      .from(SupabaseE.USER)
      .select("*")
      .eq("user_id", data.user.id);
    return userTable.data?.[0] ?? null;
  }

  return null;
};


export default async function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const user = await getUser();

  return (
    <html lang="en" suppressHydrationWarning>
      <body className="flex flex-col items-center gap-3">
        <ThemeProvider
          attribute="class"
          defaultTheme="dark"
          enableSystem
          disableTransitionOnChange
        >
          <Navbar user={user} />

          {children}
        </ThemeProvider>
      </body>
    </html>
  );
}
Answered by riský
in nextjs, it just caches for each request... so if you run the same function while rendering one request, its done only once, but if you reload the page, then if does it again
View full answer

16 Replies

wrap the getUser in cache from react and then it will use the same result for each request (only cached for one render - next request it will do it again) and then run the cached request again as it should only be done once
ye
never used it
can u summarize it a bit
in nextjs, it just caches for each request... so if you run the same function while rendering one request, its done only once, but if you reload the page, then if does it again
Answer
thanks
is it okay?
if you put a quick console.log in function and run the getuser twice, you should only see the log once per request
and now you can import this function anywhere without worrying about if it is waist of requests
thank you so much!