What is the best approach when handling the protected and unprotected routes

I designed a layout for the sign in and sign up pages with the goal of redirecting any authenticated user straight to the home page (
/
). However, when I navigate to either the sign in or sign up page while already having an active session, the page content briefly renders before the redirect occurs. Additionally, I encounter the following error:
Cannot update a component (`Router`) while rendering a different component (`AuthLayout`). To locate the bad setState() call inside `AuthLayout`, follow the stack trace as described in https://react.dev/link/setstate-in-render


Here is the relevant code:
'use client'

import Link from 'next/link'
import { usePathname, useRouter } from 'next/navigation'

import { authClient } from '@/auth/auth-client'

import { Logo } from '@/components/navigation-bar/logo'
import { Button } from '@/components/ui/button'

export const AuthLayout = ({ children }: { children: React.ReactNode }) => {
  const { data: session } = authClient.useSession()

  const router = useRouter()
  const pathname = usePathname()
  const isSignIn = pathname === '/sign-in'

  if (session) {
    router.push('/')
  }

  return (
    <div className='flex min-h-screen flex-col'>
      <header>
        <nav className='flex h-13 items-center justify-between px-4'>
          <Logo />

          {isSignIn ? (
            <Button variant='outline' asChild>
              <Link href='/sign-up'>Sign Up</Link>
            </Button>
          ) : (
            <Button variant='outline' asChild>
              <Link href='/sign-in'>Sign In</Link>
            </Button>
          )}
        </nav>
      </header>
      <div className='flex flex-1 flex-col items-center justify-center'>{children}</div>
    </div>
  )
}
Solution
import { headers } from 'next/headers';
import { redirect } from 'next/navigation';
import { auth } from '@/lib/auth';

export default async function AuthLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const user = await auth.api.getSession({
    headers: await headers(),
  });

  if (user) {
    redirect('/dashboard');
  }

  return <>{children}</>;
}
Was this page helpful?