Creating Protected Page

Protected pages are internal web app pages such as dashboard, user settings etc. These pages usually require a condition to be met, and the common case is that the user must be authenticated.

All authenticated user pages should be children of this layout - src/app/(dynamic-pages)/(authenticated-pages)/layout.tsx. Because this layout handles checking if the user is authenticated or not. If the user is not authenticated, the user will be redirected to the login page.

src/app/(dynamic-pages)/(authenticated-pages)/layout.tsx
import { ReactNode } from 'react';
import { ClientLayout } from './ClientLayout';
import { redirect } from 'next/navigation';
import { createSupabaseUserServerComponentClient } from '@/supabase-clients/user/createSupabaseUserServerComponentClient';
 
export default async function Layout({ children }: { children: ReactNode }) {
  const { data, error } =
    await createSupabaseUserServerComponentClient().auth.getUser();
  if (error || !data.user) {
    return redirect('/login');
  }
 
  return <ClientLayout>{children}</ClientLayout>;
}