Next.js Discord

Discord Forum

data fetching occurs on protected session content

Maine Coon posted this in #help-forum
Open in Discord
Maine CoonOP
Hi !
i'm using app router and i'm trying to protect and conditionnally render my page if user is not logged in.
i created a component ProtectedContentContainer which became a layout.tsx, which check if i have a nextauth session.
This solution work, but even if i'm not logged in, i call my cached data fetched on the protectedContent.

// layout.tsx
import SignInButton from "@/_components/buttons/signin-button";
import { getAuthSession } from "@/lib/auth";

const ProtectedContentContainer = async ({
}: {
  children: React.ReactNode;
}) => {
  const session = await getAuthSession();

  if (!session) {
    return (
        <SignInButton />

  return <>{children}</>;
export default ProtectedContentContainer;

// page.tsx
import BatchGrid from "@/app/batch/_components/batch-grid";
import { PageLayoutComponent } from "@/_components/layout/page-layout";
import batchService from "@/lib/batch/service";

const BatchPage = async () => {
// this is the data fetching I dont want to call if i'm not logged in
  const { data } = await batchService.getUserBatch();

  return (
    <PageLayoutComponent title="Batch">
      <div className="flex flex-col items-center justify-between flex-1">
        {data && data.batch && data.batch?.length > 0 && (
          <BatchGrid batch={data.batch} />

export default BatchPage;

- is there a way to avoid to fetch batchService.getUserBatch() on page if i'm not logged in ?
- am i missing something ?

Cheers !

0 Replies